I created a GUI with 2 input boxes and a list of checkbuttons (derived from list 'a') with scroll. Now, I want to display all the checkbuttons which have been selected.
def sel(x):
selection = "You selected the option " str(x)
label.config(text = selection)
from tkinter import *
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
root = Tk()
Label(root, text='Date from (format: 01-Apr-2022)').place(x=120,y=50)
Label(root, text='Date till (format: 21-Apr-2022)').place(x=120,y=150)
e1 = Entry(root)
e2 = Entry(root)
e1.place(x=300,y=50)
e2.place(x=300, y=150)
text = ScrolledText(root, width=50, height=60)
text.pack()
label = Label(root)
label.place(x=100, y=450)
b = [IntVar() for x in a[:10]]
for i in range(len(a[:10])):
cb = tk.Checkbutton(text, text=a[i], variable=b[i], bg='white', anchor='w', onvalue = 1, offvalue = 0, command=sel(a[i]))
text.window_create('end', window=cb)
text.insert('end', '\n')
root.mainloop()
I came up with the code above, but the resultant GUI(below) doesn't work as intended. It just displays the bottom most checkbutton even without selecting it. Further, selecting or unselecting any other checkbutton has no effect whatsoever.
CodePudding user response:
Using a sample list for list a
, since you have not provided it in the question.
Fixes
Since you are providing an argument to your function, you can use python lambda
s.
Currently, you are not passing a function to the command attribute of CheckButton, instead you are passing the returned value of sel()
.
Reference
Solution
Instead of passing the name as an argument to the function, you can iterate the list of IntVars and decide which ones are selected.
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
root = tk.Tk()
def refresh():
selected = []
for i in range(len(a)):
if b[i].get():
selected.append(a[i])
if len(selected) > 1:
label.config(text=(", ".join(selected) " are selected"))
elif len(selected) == 1:
label.config(text=(selected[0] " is selected"))
else:
label.config(text="")
tk.Label(root, text='Date from (format: 01-Apr-2022)').place(x=120,y=50)
tk.Label(root, text='Date till (format: 21-Apr-2022)').place(x=120,y=150)
e1 = tk.Entry(root)
e2 = tk.Entry(root)
e1.place(x=300,y=50)
e2.place(x=300, y=150)
text = ScrolledText(root, width=50, height=60)
text.pack()
label = tk.Label(root)
label.place(x=100, y=450)
a = ["test1", "test2", "test3", "test4"]
b = []
for i in a:
var = tk.IntVar()
b.append(var)
cb = tk.Checkbutton(text, text=i, variable=var, bg='white', anchor='w', onvalue=1, offvalue=0, command=refresh)
text.window_create('end', window=cb)
text.insert('end', '\n')
root.mainloop()