【问题标题】:Python Tkinter IntVar with Checkbutton not working带有 Checkbutton 的 Python Tkinter IntVar 不起作用
【发布时间】:2021-06-29 07:06:50
【问题描述】:

我正在从文本列表中创建 Tkinter 复选按钮。在某些情况下,我想设置默认启用的检查按钮。我分配了一个变量并将变量存储在一个列表中,以供以后检查检查按钮的状态。

但是!该变量似乎根本没有分配给检查按钮..!不知道哪里出了问题。

这是 gui 列表: (项目、文本、状态)

[('checkbox', 'Option 1', 1), ('checkbox', 'Option 2', 0), ('checkbox', 'Option 3', 1)]

还有:var = ['' for i in range (len(gui))]

这是代码:

for i in range(len(gui)):
    if (gui[i][0] == 'checkbox'):
        var[i] = tk.IntVar(value=int(gui[i][2])
        created_gui[i] = tk.Checkbutton(window, text=gui[i][1], variable=var[i], command=stateChanged) 
        created_gui[i].pack(anchor = "w")

我想设置默认启用检查按钮以防gui[i][2] == 1 但它不想工作!

完整代码:

import tkinter as tk
from tkinter import filedialog
import os

def stateChanged():
    pass

my_filetypes = [('all files', '.*'), ('text files', '.txt')]
filePath = filedialog.askopenfilename(initialdir=os.getcwd(), title="Please select a file:", filetypes=my_filetypes)
file = open(filePath, 'r')
lines = file.readlines()
gui = []

for line in lines:
    firstChar = line[0]
    text = line.strip()

    if (firstChar == '/'):
        if (text[-4:].lower() == 'true'):
            default = 1
            text = text[1:-4]
        
        elif (text[-5:].lower() == 'false'):
            default = 0
            text = text[1:-5]
        gui.append(('checkbox', text, default)) #Add checkbox to GUI
   
intVars = []
checkBtns = []
window = tk.Tk()

for i in gui:
    intVars.append(tk.IntVar(value=i[2]))
    created_gui = tk.Checkbutton(window, text=i[1], variable=intVars[-1], command=stateChanged) 
    created_gui.pack(anchor = "w")
    checkBtns.append(created_gui)

window.mainloop()

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您不需要len()range() 来循环列表,而是使用in。 要附加到列表,请使用 .append

    示例代码:

    import tkinter as tk
    
    def stateChanged():
        pass
    
    window = tk.Tk()
    gui = [('checkbox', 'Option 1', 1), ('checkbox', 'Option 2', 0), ('checkbox', 'Option 3', 1)]
    
    
    intVars = []
    checkBtns = []
    
    for i in gui:
    
        intVars.append(tk.IntVar(master=window, value=i[2]))
        created_gui = tk.Checkbutton(window, text=i[1], variable=intVars[-1], command=stateChanged) 
        created_gui.pack(anchor = "w")
        checkBtns.append(created_gui)
    
    window.mainloop()
    
    

    【讨论】:

    • @CoolCloud 对不起。我认为更改很小(只是试图提高可读性并使代码更稳定)。我什至不知道 OP 有超过 1 个 Tk() 对象。
    • @JacksonPro 您可能希望将master=window 添加到IntVar(),因为这是解决OP 问题的一部分。
    • @TheLizzard 如果人们编辑我的代码,只要他们不是出于恶意,我就没有问题。另外,我在 OP 的代码中找不到 Tk() 的两个实例。
    • @JacksonPro 我认为当 OP 在此处创建一个小示例时,他们可能已经删除了Tk() 的第二个案例。
    • @CoolCloud 好的,我以后会这样做
    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 2016-02-16
    • 1970-01-01
    • 2018-05-17
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2016-06-16
    相关资源
    最近更新 更多