如何正确获取Python Tkinter单选按钮的值?解决点击滞后等问题
Tkinter单选按钮调试问题解答
用户的调试代码:
from tkinter import * window = Tk() window.title("Python Radio Buttons") # Tkinter string variable # able to store any string value v = StringVar(window, "1") def handle_click(event): print(v.get()) for child in window.children.items(): if(type(child[1]) is Radiobutton): print("It's a radio button") # Dictionary to create multiple buttons values = {"RadioButton 1" : "1", "RadioButton 2" : "2"} # Loop is used to create multiple Radiobuttons # rather than creating each button separately for (text, value) in values.items(): rb = Radiobutton(window, text = text, variable = v, value = value) rb.bind("<Button-1>", handle_click) rb.pack(side = TOP, ipady = 5) # Infinite loop can be terminated by # keyboard or mouse interrupt # or by any predefined function (destroy()) mainloop()
问题1:点击单选按钮时v.get()返回旧值(滞后)
原因
绑定<Button-1>点击事件的时机早于Tkinter更新单选按钮关联变量v的时机。点击按钮时,handle_click先执行,此时变量还未完成更新,所以拿到的是点击前的旧值。
解决方法
替换bind("<Button-1>", handle_click)为Radiobutton自带的command参数,Tkinter会在完成变量更新后再调用指定的回调函数:
修改后的核心代码:
def handle_click(): print(v.get()) # 遍历单选按钮的逻辑可放在此处 # 创建单选按钮时替换bind为command for (text, value) in values.items(): rb = Radiobutton(window, text = text, variable = v, value = value, command=handle_click) rb.pack(side = TOP, ipady = 5)
问题2:遍历单选按钮判断选中状态
不需要额外查找特殊属性,直接通过每个单选按钮的variable和value属性对比即可:
修改后的handle_click函数示例:
def handle_click(): print(f"当前选中值:{v.get()}") # 遍历窗口内的单选按钮 for child in window.children.values(): if isinstance(child, Radiobutton): # 判断当前单选按钮是否被选中 is_checked = child['variable'].get() == child['value'] print(f"按钮「{child['text']}」选中状态:{is_checked}")
说明
- 用
isinstance(child, Radiobutton)代替type(child[1]) is Radiobutton,类型判断更严谨 - 通过
child['variable'].get()获取关联变量的当前值,和按钮自身的value对比,即可判断是否选中
内容的提问来源于stack exchange,提问作者ds_practicioner
相关产品推荐
相关产品推荐

