有没有一种简单的方法可以让右键菜单只在 texty 上打开而不是在整个窗口上打开?
这是一个快速混搭来说明我的问题。从第 25 行的 texty 继承是在黑暗中的一个镜头,这不起作用,但它接近一个简单的解决方案,就像我正在寻找的那样。每次我想设置右键菜单时,我都希望避免对整个班级进行编程。
from tkinter import *
from tkinter import ttk
def menu_popup(event):
try:
popup.tk_popup(event.x_root, event.y_root, 0)
finally:
popup.grab_release()
win = Tk()
win.geometry("600x550+125+125")
e = Entry(win, width=50, font=('Helvetica', 11))
e.pack()
e.insert(0, "Some text....")
label = Label(win, text="Right-click to see a menu", font= ('Helvetica 18'))
label.pack(pady= 40)
texty=Text(win, height=10)
texty.pack()
popup = Menu(texty, tearoff=0)
popup.add_command(label="New")
popup.add_separator()
popup.add_command(label="Open")
popup.add_separator()
popup.add_command(label="Close")
win.bind("<Button-3>", menu_popup)
button = ttk.Button(win, text="Quit", command=win.destroy)
button.pack()
mainloop()
应为相应事件执行回调的小部件由您调用的小部件决定bind
(以及绑定级别*)。因此,如果您希望在 中识别事件texty
,则对其应用绑定。
texty.bind("<Button-3>", menu_popup)
*bind_all
无论哪个小部件具有焦点或被调用,它都会执行。阅读54.1。绑定级别以获取更多信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句