Tkinter技术求助:点击Checkbutton时打印对应选项名称的实现方案
解决方案
要实现点击Checkbutton时打印对应选项名称,只需修改check函数,并在创建Checkbutton时通过lambda传递当前选项名称即可。
修改后的完整代码
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(interest_name): # 打印当前点击的复选框选项名称 print(f"点击了选项: {interest_name}") 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): # 使用lambda绑定当前选项s到check函数的参数 Checkbutton(root, text=s, variable=chks[i], command=lambda name=s: check(name)).pack(anchor=W) Button(root, text="submit", command=on_click).pack() root.mainloop()
关键说明
- 修改
check函数,添加interest_name参数,用于接收并打印当前点击的选项名称。 - 在创建Checkbutton时,将
command设置为lambda name=s: check(name),通过lambda把当前循环的选项名称s绑定到check函数的参数上,确保点击每个复选框时能传递对应的选项名。
内容的提问来源于stack exchange,提问作者HOW TO
相关产品推荐
相关产品推荐

