在 Python 中用鼠标光标悬停在某物上时显示消息 [英] Display message when hovering over something with mouse cursor in Python

查看:137
本文介绍了在 Python 中用鼠标光标悬停在某物上时显示消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 TKinter 在 Python 中制作的 GUI.我希望能够在我的鼠标光标移动到标签或按钮顶部时显示一条消息.这样做的目的是向用户解释按钮/标签的作用或代表什么.

I have a GUI made with TKinter in Python. I would like to be able to display a message when my mouse cursor goes, for example, on top of a label or button. The purpose of this is to explain to the user what the button/label does or represents.

有没有办法在 Python 中将鼠标悬停在 tkinter 对象上时显示文本?

Is there a way to display text when hovering over a tkinter object in Python?

推荐答案

您需要在 事件上设置绑定.

You need to set a binding on the <Enter> and <Leave> events.

注意:如果您选择弹出窗口(即:工具提示),请确保不要直接在鼠标下方弹出.将会发生的事情是它会导致一个 leave 事件触发,因为光标离开标签并进入弹出窗口.然后,您的离开处理程序将关闭窗口,您的光标将进入标签,这将导致一个 enter 事件,该事件弹出该窗口,这将导致一个离开事件,该事件关闭该窗口,这将导致一个进入事件,...广告无限.

Note: if you choose to pop up a window (ie: a tooltip) make sure you don't pop it up directly under the mouse. What will happen is that it will cause a leave event to fire because the cursor leaves the label and enters the popup. Then, your leave handler will dismiss the window, your cursor will enter the label, which causes an enter event, which pops up the window, which causes a leave event, which dismisses the window, which causes an enter event, ... ad infinitum.

为简单起见,这里有一个更新标签的示例,类似于某些应用使用的状态栏.创建工具提示或其他显示信息的方式仍然以绑定到 的相同核心技术开始.

For simplicity, here's an example that updates a label, similar to a statusbar that some apps use. Creating a tooltip or some other way of displaying the information still starts with the same core technique of binding to <Enter> and <Leave>.

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.l1 = tk.Label(self, text="Hover over me")
        self.l2 = tk.Label(self, text="", width=40)
        self.l1.pack(side="top")
        self.l2.pack(side="top", fill="x")

        self.l1.bind("<Enter>", self.on_enter)
        self.l1.bind("<Leave>", self.on_leave)

    def on_enter(self, event):
        self.l2.configure(text="Hello world")

    def on_leave(self, enter):
        self.l2.configure(text="")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand="true")
    root.mainloop()

这篇关于在 Python 中用鼠标光标悬停在某物上时显示消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆