【发布时间】: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()
【问题讨论】: