I just started coding less than 3 weeks ago (took a class in Lynda) and now working on a GUI that enable user to tick/untick a lists. I manage to get it done but in inefficient workaround (someone gave me a heads up on this).
What i have done basically calling a variables for each checkbox and insert the checkbox states into it. So if I have 100 of checkboxes in the list, I will need to create 100 variables. Below is the working code that I wrote.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
var1t1 = tk.IntVar()
var2t1 = tk.IntVar()
var3t1 = tk.IntVar()
var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")
def boxstates_t1():
var_name = [var1t1.get(), var2t1.get(), var3t1.get()]
print(var_name)
# -----------------Checkbox-----------------
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
check1_t1 = ttk.Checkbutton(root, text = "Mike", variable = var1t1)
check1_t1.pack(anchor = tk.W)
check2_t1 = ttk.Checkbutton(root, text = "Harry", variable = var2t1)
check2_t1.pack(anchor = tk.W)
check3_t1 = ttk.Checkbutton(root, text = "Siti", variable = var3t1)
check3_t1.pack(anchor = tk.W)
# -----------------Button-----------------
btn2 = ttk.Button(root, text="Show", command = boxstates_t1)
btn2.pack(side=tk.RIGHT)
root.mainloop()
Then i googled around and found few code that lead me to use for loop to print the list. I initialize the var_name = []
so that it will capture each checkbox state from the list.
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
var1 = tk.IntVar()
var_name = []
root.title("Testing Checkbox")
root.geometry("200x150")
def boxstates():
var_name = var1.get()
print(var_name)
# ------------------Chekbox-------------
name1 = ["Mike", "Harry", "Siti"]
labelName = tk.Label(root, text = "Name")
labelName.pack(anchor = tk.W)
for checkboxname in name1:
check1_t1 = ttk.Checkbutton(root, text=checkboxname, variable=var1)
check1_t1.pack(anchor = tk.W)
# ------------------Button-------------
btn2 = ttk.Button(root, text="Show", command = boxstates)
btn2.pack(side=tk.RIGHT)
root.mainloop()
But I was unable to tick the checkbox independently and the print out result also comes back as if it's in single variable. Am I doing the array var_name = []
wrongly? I'm currently lost and have no clue where to head next.
Any advise is greatly appreciate.
Aucun commentaire:
Enregistrer un commentaire