【问题标题】:How to bind the pop up menu to a label in Tkinter如何将弹出菜单绑定到 Tkinter 中的标签
【发布时间】:2018-12-28 12:45:19
【问题描述】:

我想限制可以触发弹出菜单的区域

当用户右键单击时,我当前的代码允许在 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()

我希望仅在用户右键单击“右键单击显示菜单”标签时触发弹出菜单

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    您的代码完全按照设计运行。您创建了一个非常大的标签小部件(40 个字符宽,20 个字符高,或大约 350x325 像素,具体取决于您的系统字体和分辨率设置)。因此,当您认为您在标签外部单击时,您并没有,因为它占据了整个窗口。

    要明白我的意思,请为您的标签添加独特的背景颜色。例如:

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

    上面的结果如下图所示。您单击的任何粉红色的地方都是标签的一部分,因此将显示菜单。

    【讨论】:

    • 如果答案对您有用,为什么不接受并投票?
    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 1970-01-01
    • 2016-04-15
    相关资源
    最近更新 更多