简体   繁体   English

如何在Tkinter中将弹出菜单绑定到标签

[英]How to bind the pop up menu to a label in Tkinter

I want to limit the area where the popup menu can be triggered 我想限制可以触发弹出菜单的区域

My current code allows the popup menu be triggered anywhere in the tkinter window when the user right clicks 我当前的代码允许在用户右键单击时在tkinter窗口中的任何位置触发弹出菜单

from tkinter import *

root = Tk()

w = Label(root, text="Right-click to display menu", width=40, height=20)
w.pack()


popup = Menu(root, tearoff=0)
popup.add_command(label="Next") # , command=next) etc...
popup.add_command(label="Previous")
popup.add_separator()
popup.add_command(label="Home")

def do_popup(event):

    try:
        popup.tk_popup(event.x_root, event.y_root, 0)
    finally:
        popup.grab_release()

w.bind("<Button-3>", do_popup)

b = Button(root, text="Quit", command=root.destroy)
b.pack()

mainloop()

I want the popup menu to be triggered when the user right clicks over the label "Right-click to display menu" only 我希望仅在用户右键单击标签“右键单击以显示菜单”时触发弹出菜单

Your code is working exactly as designed. 您的代码完全按照设计工作。 You've created a really huge label widget (40 characters wide, 20 characters high, or roughly 350x325 pixels depending on your system font and resolution settings). 您已经创建了一个非常大的标签窗口小部件(宽40个字符,高20个字符或大约350x325像素,具体取决于您的系统字体和分辨率设置)。 So while you think you're clicking outside the label, you're not since it takes up the whole window. 因此,尽管您认为自己在标签之外单击,但并不是因为它占据了整个窗口。

To see what I mean, give your label a distinctive background color. 要了解我的意思,请为您的标签添加独特的背景色。 For example: 例如:

w = Label(root, text="Right-click to display menu", width=40, height=20, background="pink")

The above results in a window that looks like the following image. 上面的结果是一个看起来像下图的窗口。 Anywhere you click that is pink is part of the label, and thus will show the menu. 您单击的任何地方,粉红色都是标签的一部分,因此将显示菜单。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM