AttributeError:“Checkbutton”对象没有“取消选择”属性

2024-09-30 10:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

从包含“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()

但它给出了一个错误:

回溯(最近一次呼叫最后一次): 文件“C:/Users/jmamuham/PycharmProjects/LogBook/load_state.py”,第24行,在 createCheckboxes() 文件“C:/Users/jmamuham/PycharmProjects/LogBook/load_state.py”,第20行,在CreateCheckbox中 选中。取消选择() AttributeError:“Checkbutton”对象没有“取消选择”属性

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

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


Tags: testimporttxttkinter状态defcheckroot
2条回答
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'

有一种比选择()和取消选择()更简单的方法!如果将checkbutton正确链接到tkinter int或boolean变量,则checkbutton将分别自动检查和取消检查给定的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()

相关问题 更多 >

    热门问题