pythontkintertkinter.checkbutton

When you press the Checkbutton, i want the name to be printed out


When you press the Checkbutton, i want the name to be printed out.

Please help me find a solution of the problem, thanks.

from tkinter import *


def on_click():

    lst = [interests[i] for i, chk in enumerate(chks) if chk.get()]
    print(lst)
    print(",".join(lst))

def check():
    print()
    pass
interests = ['Music', 'Book', 'Movie', 'Photography', 'Game', 'Travel']
root = Tk()
root.option_add("*Font", "impact 30")
chks = [BooleanVar() for i in interests]

Label(root, text="Your interests", bg="gold").pack()
for i, s in enumerate(interests):
    Checkbutton(root, text=s, variable=chks[i] , command=check).pack(anchor=W)  # W = West

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

Solution

  • Like this:

    from tkinter import *
    
    def on_click():
        lst = [interests[i] for i, chk in enumerate(chks) if chk.get()]
        print(lst)
        print(",".join(lst))
    
    def check(s):
        print(s)
    
    interests = ['Music', 'Book', 'Movie', 'Photography', 'Game', 'Travel']
    root = Tk()
    root.option_add("*Font", "impact 30")
    chks = [BooleanVar() for i in interests]
    
    Label(root, text="Your interests", bg="gold").pack()
    for i, s in enumerate(interests):
        Checkbutton(root, text=s, variable=chks[i] , command=lambda s=s: check(s)).pack(anchor=W)  # W = West
    
    Button(root, text="submit", command=on_click).pack()
    root.mainloop()