我正在为一个医疗工具制作一个GUI作为一个类项目。鉴于条件,它应该输出从webMD等不同网站收集的一系列治疗选项。我希望能够处理列出的任何治疗方法的鼠标悬停事件,以提供有关治疗的更多信息(例如药物类别,是否为通用治疗等)。
标签存储在一个列表中,因为我不知道预先会返回多少种不同的治疗方法。所以我的问题是如何让这些鼠标悬停事件发挥作用。我无法为每个可能的标签编写函数定义,它们的数量将达到数百或数千。我确信有一种非常pythonic的方式,但我不知道是什么。
以下是我创建标签的代码:
def search_click():
"""
Builds the search results after the search button has been clicked
"""
self.output_frame.destroy() # Delete old results
build_output() # Rebuild output frames
treament_list = mockUpScript.queryConditions(self.condition_entry.get()) # Get treatment data
labels = []
frames = [self.onceFrame, self.twiceFrame, self.threeFrame, self.fourFrame] # holds the list of frames
for treament in treament_list: # For each treatment in the list
label = ttk.Label(frames[treament[1] - 1], text=treament[0]) # Build the label for treatment
labels.append(label) # Add the treatment to the list
label.pack()
根据您的鼠标悬停在哪种药物上,应该更改“悬停在药物上以获取信息”的文字。
答案 0 :(得分:3)
我无法为每个可能的标签编写函数定义,它们的数量将达到数百或数千。我确信有一种非常pythonic的方式,但我不知道是什么。
查看lambda functions几乎与您想要的完全相同的内容。
在您的情况下,例如:
def update_bottom_scroll_bar(text):
# whatever you want to do to update the text at the bottom
for treatment in treament_list: # For each treatment in the list
label = ttk.Label(frames[treatment[1] - 1], text=treatment[0]) # Build the label for treatment
label.bind("<Enter>", lambda event, t=treatment: update_bottom_scroll_bar(text=t))
label.bind("<Leave>", lambda event: update_bottom_scroll_bar(text='Default label text'))
labels.append(label) # Add the treatment to the list
label.pack()
另请拼写您的变量,我已将treament
更正为treatment
...