I have a list of multiple strings. I want the user to choose one or more of these strings through a GUI interface. For example, if my list is l = ["apple", "ball", "cat", "dog"]
, I want the GUI to show
JavaScript
x
5
1
□ apple
2
□ ball
3
□ cat
4
□ dog
5
I also want to read the inputs given by the user. How can I generate checkboxes for each of these strings dynamically and read the inputs given by the user using tkinter?
Advertisement
Answer
Try this:
JavaScript
1
23
23
1
import tkinter as tk
2
3
4
window = tk.Tk()
5
window.title('My Window')
6
window.geometry('100x200')
7
8
def on_click():
9
lst = [l[i] for i, chk in enumerate(chks) if chk.get()]
10
print(",".join(lst))
11
12
l = ["apple", "ball", "cat", "dog"]
13
14
chks = [tk.BooleanVar() for i in l]
15
16
for i, s in enumerate(l):
17
tk.Checkbutton(window, text=s, variable=chks[i]).pack(anchor=tk.W)
18
19
tk.Button(window, text="submit", command=on_click).pack()
20
21
22
window.mainloop()
23
Result output: