You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

tkinter中Radiobutton单选框鼠标悬停时自动被选中的问题如何解决

问题原因
  • 核心是单选框绑定的StringVar变量被提前回收:你把list_of_months_variable定义在select_months函数内部,属于局部变量,函数执行完毕后这个变量就会被Python垃圾回收,Radiobutton和变量的绑定关系失效,就会出现悬停自动选中的异常交互。
  • 次要诱因是变量没有初始化默认值:StringVar初始默认值为空字符串,单选组没有匹配的默认选中项,也会放大绑定异常的问题。
修复方案

只需要修改两处即可:

  1. 把StringVar绑定到弹窗对象上,避免作为局部变量被回收
  2. 给StringVar设置初始值

修改后的对应代码片段如下:

# 替换原有变量定义逻辑
new_window.list_of_months_variable = StringVar()
# 可自定义初始值,设为第一个选项或者空字符串(默认不选)都可以
new_window.list_of_months_variable.set("January")

# 循环创建Radiobutton时,variable参数改成绑定到窗口的变量
Radiobutton(new_window, text=i, variable=new_window.list_of_months_variable, value=str(i)).grid(padx=4, row=xrow, column=ycolumn)

完整修复后的可运行代码:

from tkinter import *

p = Tk()

def select_months():
    new_window = Toplevel()
    new_window.resizable(width=FALSE, height=FALSE)

    days_label = Label(new_window,text="Select month")
    days_label.grid()

    ycolumn = 0
    xrow = 1

    list_of_months = ["January", "February ", "March ", "April "]
    # 把变量绑定到窗口对象,避免被回收
    new_window.list_of_months_variable = StringVar()
    # 初始化默认值
    new_window.list_of_months_variable.set("January")

    for i in list_of_months:
        Radiobutton(new_window, text=i, variable=new_window.list_of_months_variable, value=str(i)).grid(padx=4, row=xrow, column=ycolumn)
        ycolumn += 1

        if ycolumn > 2:
            ycolumn = 0
            xrow += 1

    ok_button = Button(new_window, text="OK", command=new_window.destroy).grid()
        
select_month_label = Label(p,text="which month ? : ").pack(side="left")
select_month_button = Button(p, text="months...", command=select_months).pack()

p.mainloop()

内容的提问来源于stack exchange,提问作者alfaplt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 12:42:00