在Tkin中列出鼠标悬停事件函数

2024-04-25 17:39:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个医学工具的图形用户界面作为一个类项目。给定一个条件,它应该输出一堆从不同网站收集的治疗方案,比如webMD。我希望能够处理所列出的任何一种疗法的鼠标悬停事件,以提供关于该疗法的更多信息(例如药物的类别,是否为普通药物,等等)。在

标签存储在一个列表中,因为我不知道有多少不同的处理将被退回。所以我的问题是如何让这些mouseover事件起作用。我不能为每一个可能的标签都写一个函数定义,它们的数量可能是成百上千。我肯定有一个非常Python式的方法来做,但我不知道是什么。在

以下是我创建标签的代码:

    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

文本“悬停在药物上获取信息”应该根据鼠标悬停在哪种药物上而改变。在


Tags: theselfoutputsearchframeslabels事件标签
1条回答
网友
1楼 · 发布于 2024-04-25 17:39:12

I can't write a function definition for every single possible label, they would number in the hundreds or thousands. I'm sure there's a very pythonic way to do it, but I have no idea what.

检查一下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。。。在

相关问题 更多 >