tkinter循环创建按钮悬停变色仅最后一个生效问题求助
问题根源
你遇到的问题是Python闭包的晚绑定特性导致的:循环内定义的事件回调函数引用的ResultsButtons变量不会在函数定义时捕获当前迭代的按钮实例,只会在函数被触发调用时才查找变量值,此时循环已执行完成,ResultsButtons固定指向最后一次迭代创建的按钮,因此所有悬停事件只会修改最后一个按钮的背景色。
修复方案
方案1:利用事件对象获取触发控件(最简洁,推荐)
事件绑定的回调函数会自动接收event参数,其中event.widget属性就是触发当前事件的控件,无需依赖外部变量,可直接把两个回调函数移到循环外定义:
# 提前定义全局公用的事件回调函数 def on_enter_results(event): event.widget['background'] = Hover winsound.PlaySound('Hover.wav', winsound.SND_ASYNC) def on_leave_results(event): event.widget['background'] = BackGroundColor # 原有查询逻辑不变 SearchSelection = SearchVar.get() SearchParameter = txtSearch.get() conn = sqlite3.connect("EasyClinic.db") cursor = conn.cursor() # 补充提醒:此处直接拼接SearchSelection存在SQL注入风险,建议提前做字段名白名单校验 cursor.execute ("SELECT * FROM patients WHERE (%s) = (?)" %(SearchSelection), (SearchParameter,)) results = cursor.fetchall() conn.commit() conn.close() if len(results) == 0: print("No result found") else: for result in results: ResultsButtons = tk.Button(canvasResult, text=result, bg=BackGroundColor, fg=ForeGroundColor, relief='flat', font=MyFont2, width=65, height=2) ResultsButtons.pack(pady=5) ResultsButtons.bind("<Enter>", on_enter_results) ResultsButtons.bind("<Leave>", on_leave_results)
方案2:用默认参数捕获当前迭代的按钮实例
如果你需要把回调函数定义在循环内部,可以通过默认参数的特性,在函数定义时就把当前迭代的按钮实例绑定到函数内部:
# 原有查询逻辑不变 SearchSelection = SearchVar.get() SearchParameter = txtSearch.get() conn = sqlite3.connect("EasyClinic.db") cursor = conn.cursor() # 补充提醒:此处直接拼接SearchSelection存在SQL注入风险,建议提前做字段名白名单校验 cursor.execute ("SELECT * FROM patients WHERE (%s) = (?)" %(SearchSelection), (SearchParameter,)) results = cursor.fetchall() conn.commit() conn.close() if len(results) == 0: print("No result found") else: for result in results: ResultsButtons = tk.Button(canvasResult, text=result, bg=BackGroundColor, fg=ForeGroundColor, relief='flat', font=MyFont2, width=65, height=2) ResultsButtons.pack(pady=5) # 用默认参数btn=ResultsButtons捕获当前迭代的按钮实例 def on_enter_results(event, btn=ResultsButtons): btn['background'] = Hover winsound.PlaySound('Hover.wav', winsound.SND_ASYNC) def on_leave_results(event, btn=ResultsButtons): btn['background'] = BackGroundColor ResultsButtons.bind("<Enter>", on_enter_results) ResultsButtons.bind("<Leave>", on_leave_results)
内容的提问来源于stack exchange,提问作者Essam Sammour
相关产品推荐
相关产品推荐

