通过tkinter按钮循环操作不正常



我正在编写一段新代码,使用循环在按钮上显示sqlite搜索结果。除1个问题外,代码工作正常。我写了一个函数来改变背景颜色,并在悬停在按钮上时播放声音。问题是,当我将鼠标悬停在结果的任何按钮上时,颜色只会在最后一个按钮上发生变化,尽管声音播放没有问题。以下是涉及的代码部分:

SearchSelection = SearchVar.get()
SearchParameter = txtSearch.get()
conn = sqlite3.connect("EasyClinic.db")
cursor = conn.cursor()
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)
def on_enter_results(result):
ResultsButtons['background'] = Hover
winsound.PlaySound ('Hover.wav', winsound.SND_ASYNC)
def on_leave_results(result):
ResultsButtons['background'] = BackGroundColor  
ResultsButtons.bind("<Enter>", on_enter_results)
ResultsButtons.bind("<Leave>", on_leave_results)

请提供帮助感谢

您可以更改on_enter_results()on_leave_results()这两个函数,如下所示:

def on_enter_results(event):
# event.widget is the widget that triggers this event
event.widget['background'] = Hover
winsound.PlaySound ('Hover.wav', winsound.SND_ASYNC)
def on_leave_results(event):
event.widget['background'] = BackGroundColor

实际上,您可以将这两个函数移到for循环之外(即在for循环之前(。

问题是python总是用最新的按钮覆盖ResultsButtons变量,这在调用函数on_enter_results或on_eleave_results时会出现问题,因为它使用了覆盖的ResultsButton变量。解决方案是更直接地指定按钮,并将其传递给具有lambda函数的函数。我不能检查这个代码是否有效,因为我没有完整的例子,但像这样的东西应该有效:

if len(results) == 0:
print ("No result found")
else:
def on_enter_results(event_info, resbutton):
resbutton['background'] = Hover
winsound.PlaySound ('Hover.wav', winsound.SND_ASYNC)
def on_leave_results(event_info, resbutton):
resbutton['background'] = BackGroundColor  
for result in results:
ResultsButton = tk.Button(canvasResult, text=result, bg=BackGroundColor, fg=ForeGroundColor, relief='flat', font=MyFont2, width=65, height=2)
ResultsButton.pack(pady=5)
ResultsButton.bind("<Enter>", lambda event_info, btn=ResultsButton: on_enter_results(btn))
ResultsButton.bind("<Leave>", lambda event_info, btn=ResultsButton: on_leave_results(btn))

为了更好地了解正在发生的事情:Python常见问题

它由acw1668解决。感谢大家对的支持

最新更新