Home > Blockchain >  Get values from checkboxes in Tkinter
Get values from checkboxes in Tkinter

Time:10-17

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

□ apple
□ ball 
□ cat 
□ dog

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?

CodePudding user response:

Try this:

import tkinter as tk


window = tk.Tk()
window.title('My Window')
window.geometry('100x200')
 
def on_click():
    lst = [l[i] for i, chk in enumerate(chks) if chk.get()]
    print(",".join(lst))    
 
l = ["apple", "ball", "cat", "dog"]

chks = [tk.BooleanVar() for i in l]

for i, s in enumerate(l):
    tk.Checkbutton(window, text=s, variable=chks[i]).pack(anchor=tk.W)

tk.Button(window, text="submit", command=on_click).pack()
     
  
window.mainloop()

Result output:

enter image description here

  • Related