0

我在从包含“0”和“1”的文本文件中加载复选框状态时遇到问题。

inside "test.txt" file :

1
0
1
0

这就是我期望的结果,“1”代表选中框,“0”代表未选中框

在此处输入图像描述

下面是我正在处理的代码:

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry("180x90")
name1 = ["Mike", "Harry", "Siti", "Jenn"]

def loadstates():
    f = open("test.txt", "r")
    list_a = []
    list_a = f.readlines()
    return list_a
    f.close()

def createCheckboxes():
    for x, y in zip(st, name1):
        check = ttk.Checkbutton(root, text=y, variable=x)
        if x=='0':
            check.select()
        else:
            check.deselect()
        check.pack(anchor=tk.W)

st = loadstates()
createCheckboxes()
root.mainloop()

但它给出了错误:

回溯(最后一次调用):文件“C:/Users/jmamuham/PycharmProjects/LogBook/load_state.py”,第 24 行,在 createCheckboxes() 文件“C:/Users/jmamuham/PycharmProjects/LogBook/load_state.py”中,第 20 行,在 createCheckboxes check.deselect() AttributeError: 'Checkbutton' object has no attribute 'deselect'

知道为什么 .select() 和 .deselect() 给我这个错误吗?

顺便说一句,我是否使用正确的方法使用 1 和 0 重新填充复选框状态?

4

2 回答 2

0

还有比 select() 和 deselect() 更简单的方法!如果您将检查按钮正确链接到 tkinter int 或布尔变量,则检查按钮将自动检查和取消检查是否分别给出 1/True 或 0/False 值。就是这样:

import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.geometry("180x90")
name1 = ["Mike", "Harry", "Siti", "Jenn"]

def loadstates():
    f = open("test.txt", "r")
    list_a = []
    list_a = f.readlines()
    f.close()
    return [int(i) for i in list_a] # Make sure your values are integers, not strings

def createCheckboxes():
    for value, y in zip(st, name1):
        x = tk.IntVar() # This is a tkinter variable. BooleanVar() will also work here
        x.set(value) # When modifying values of a tkinter variable, always use .set()
        check = ttk.Checkbutton(root, text=y, variable=x)
        check.var = x # Link the variable to the checkbutton so it isn't thrown out by garbage collection
        check.pack(anchor=tk.W)

st = loadstates()
createCheckboxes()
root.mainloop()
于 2020-01-24T07:44:44.137 回答
0
import tkinter as tk
root = tk.Tk()
root.geometry("180x90")
name1 = ["Mike", "Harry", "Siti", "Jenn"]

def loadstates():
    f = open("test.txt", "r")
    list_a = []
    list_a = f.readlines()
    f.close()
    return list_a

def createCheckboxes():
    for x, y in zip(st, name1):
        check = tk.Checkbutton(root, text=y, variable=x)
        if x.strip()=='0':
            check.select()
        else:
            check.deselect()
        check.pack(anchor=tk.W)

st = loadstates()
createCheckboxes()
root.mainloop()

利用tk.Checkbutton

利用x.strip()=='0'

于 2020-01-24T07:57:15.690 回答