I am creating Tkinter checkbuttons from a list of text. I want to set checkbutton enabled by default in some cases. I assign a variable and store the variable in a list to be used later to check the state of checkbutton.
However. The variable doesn't seem to be assigned to the checkbutton at all..! I don't know where is the problem.
This is the gui list: (item, text, state)
[('checkbox', 'Option 1', 1), ('checkbox', 'Option 2', 0), ('checkbox', 'Option 3', 1)]
And: var = ['' for i in range (len(gui))]
This is the code:
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")
I want to set the checkbutton enabled by default in case gui[i][2] == 1
but it doesn't want to work!
Full Code:
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()
you don't need len()
and range()
to loop through the list instead use in
. To append to a list use .append
sample code:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.