[从txt文件-Tkinter加载复选框状态

问题描述 投票:0回答:1

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

inside "test.txt" file :

1
0
1
0

这是我期望的结果,因为'1'表示复选框,而'0'表示未选中框

enter image description here

下面是我正在使用的代码:

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()

但是它给出了错误:[AttributeError:'Checkbutton'对象没有属性'deselect'

任何想法为什么.select()和.deselect()都会给我这个错误?

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

python tkinter
1个回答
0
投票

还有比select()和deselect()更简单的方法!如果您将检查按钮正确链接到tkinter int或boolean变量,则该检查按钮将自动检查和取消检查是否分别为其指定了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()
    return [int(i) for i in list_a] # Make sure your values are integers, not strings
    f.close()

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()
© www.soinside.com 2019 - 2024. All rights reserved.