0

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()
HOW TO
  • 5
  • 2

1 Answers1

0

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()
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • wow can you explain this part please? `command=lambda s=s: check(s))` – HOW TO Jul 21 '22 at 06:40
  • Tkinter calls the commands with no parameters. You need a parameter. So, the `lambda` is basically a mini function that lets us call something else. The `s=s` thing is a Python trick, because without it, the call gets the ENDING value of `s`, not the value in each loop. – Tim Roberts Jul 21 '22 at 07:34