在Tkinter中列出鼠标悬停事件函数的列表

3
我正在为一个医疗工具创建GUI作为课程项目。给定一种条件,它应该从不同的网站(如WebMD)输出一堆治疗方案。我希望能够处理任何列出的治疗措施的mouseover事件,以提供有关治疗措施的更多信息(例如药物类别、是否为通用药等)。
这些标签存储在列表中,因为我不知道会返回多少不同的治疗方案。所以我的问题是如何使这些mouseover事件起作用。我不能为每个可能的标签编写一个函数定义,它们的数量将达到数百或数千个。我相信有一种非常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()        

这是 GUI 的外观(请勿评判 [-; )GUI image

文本“Hover over drugs for information”应根据您的鼠标悬停在哪种药物上而进行更改。


我不理解你的代码,你命名函数为 search_click 但看起来你在询问鼠标悬停代码?你也没有明确指示实际的悬停文本在哪里以及是什么 - 你只想要物品的名称吗?还是这是从文件中提取的? - enderland
是的,当有人点击搜索按钮时,函数search_click被运行,因此在点击之前不会显示任何药品。因此,与mouseover事件相关的任何操作都必须在此之后发生。我主要包括此代码是为了让人们了解标签是如何创建的。最终,这些信息可能会来自另一个文件,但现在我只需要药品的名称,以便我知道如何做。 - bendl
1个回答

3
我无法为每个可能的标签编写函数定义,它们会有数百或数千个。我相信有一种非常Pythonic的方法来做到这一点,但我不知道是什么。

请查看lambda函数,它们几乎与您想要的完全相同。

在您的情况下,可以尝试以下代码:

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...

哎呀,代码自动补全的一个缺点就是会让拼写错误一直存在哈哈。 - bendl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接