将鼠标悬停在tkinter按钮上 [英] Mouseover on tkinter button

查看:101
本文介绍了将鼠标悬停在tkinter按钮上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将光标悬停在按钮上时,是否可以获得弹出选项(代码中的弹出功能)?

Is it possible to get the popup option (pop function in the code) on hovering the cursor on the button?

import tkinter as tk
from tkinter import Tk, BOTH, Menu

def pop(bt):
    try:
        x = bt.winfo_rootx()+238
        y = bt.winfo_rooty()+10
        popup.tk_popup(x, y, 0)
    finally:
        popup.grab_release()


root = tk.Tk()

popup = Menu(root, tearoff=0,relief='raised')
popup.add_command(label="About")
popup.add_command(label="User manual")
popup.add_command(label="Contact us")

button1 =tk.Button(root, text="HELP",height=3,width=26,command=lambda: controller.show_frame(HelpPage))                   
button1.configure(command = lambda: pop(button1))
button1.place(x=0,y=0
              )
root.mainloop()

.

button1.bind('<Enter>',pop(button1)) #gives the following output without the mouse cursor over that button.

推荐答案

您需要< Enter> < Leave> 绑定序列来映射和取消映射菜单.Tkinter Menu 有两种方法 post unpost ,其中 post 显示给定坐标的菜单,而 unpost将其隐藏起来.不幸的是,我无法对其进行测试,因为取消发布功能无法在macOS或Linux

You need <Enter> and <Leave> bind sequences to map and unmap the Menu. Tkinter Menu has two methods post and unpost where post shows the menu at given coordinates, and unpost hides it away. Unfortunately, I couldn't test it as the unpost functionality doesn't work on macOS or Linux [refer to this link for the same]. I also changed the x, y coords to map the Menu in the center of the widget (Button), it can be changed if required.

这是完整的示例代码.

import tkinter as tk
from tkinter import Tk, BOTH, Menu


def pop(evt):
    but = evt.widget
    if str(evt.type) == "Enter":
        # Map the menu in the center of the width.
        x = but.winfo_rootx() + int(but.winfo_width()/2)
        y = but.winfo_rooty() + int(but.winfo_height()/2)
        popup.tk_popup(x, y)

    elif str(evt.type) == "Leave":
        popup.unpost()


root = tk.Tk()
root.geometry("300x300")

popup = Menu(root, tearoff=0, relief='raised')
popup.add_command(label="About")
popup.add_command(label="User manual")
popup.add_command(label="Contact us")

button1 = tk.Button(root, text="HELP", height=3, width=26)
button1.bind('<Enter>', pop)
button1.bind('<Leave>', pop)
button1.pack(pady=100)

root.mainloop()

就像说的那样, unpost 不适用于macOS或Linux,因此我无法100%测试示例代码,但应该可以正常工作.

Like said, unpost doesn't work on macOS or Linux, so I couldn't test the sample code 100% but it should work fine.

这篇关于将鼠标悬停在tkinter按钮上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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