我有一个 python-tkinter gui 应用程序,我一直在尝试找到一些方法来添加一些功能。我希望有一种方法可以右键单击应用程序列表框区域中的项目并调出上下文菜单。 tkinter 能够做到这一点吗?看看 gtk 或其他一些 gui-toolkit 会更好吗?
最佳答案
您将创建一个 Menu实例化并编写一个调用
的函数
它的 post()
或 tk_popup()
方法。
tkinter documentation目前没有任何关于 tk_popup()
的信息.
阅读 Tk documentation描述或来源:
library/menu.tcl
in the Tcl/Tk source :
::tk_popup -- This procedure pops up a menu and sets things up for traversing the menu and its submenus. Arguments: menu - Name of the menu to be popped up. x, y - Root coordinates at which to pop up the menu. entry - Index of a menu entry to center over (x,y). If omitted or specified as {}, then menu's upper-left corner goes at (x,y).
tkinter/__init__.py
in the Python source:
def tk_popup(self, x, y, entry=""):
"""Post the menu at position X,Y with entry ENTRY."""
self.tk.call('tk_popup', self._w, x, y, entry)
您将上下文菜单调用功能与右键单击相关联:
the_widget_clicked_on.bind("<Button-3>", your_function)
.
但是,与右键单击相关的数字在每个平台上并不相同。
library/tk.tcl
in the Tcl/Tk source :
On Darwin/Aqua, buttons from left to right are 1,3,2. On Darwin/X11 with recent XQuartz as the X server, they are 1,2,3; other X servers may differ.
Here is an example I wrote that adds a context menu to a Listbox:
import tkinter # Tkinter -> tkinter in Python 3
class FancyListbox(tkinter.Listbox):
def __init__(self, parent, *args, **kwargs):
tkinter.Listbox.__init__(self, parent, *args, **kwargs)
self.popup_menu = tkinter.Menu(self, tearoff=0)
self.popup_menu.add_command(label="Delete",
command=self.delete_selected)
self.popup_menu.add_command(label="Select All",
command=self.select_all)
self.bind("<Button-3>", self.popup) # Button-2 on Aqua
def popup(self, event):
try:
self.popup_menu.tk_popup(event.x_root, event.y_root, 0)
finally:
self.popup_menu.grab_release()
def delete_selected(self):
for i in self.curselection()[::-1]:
self.delete(i)
def select_all(self):
self.selection_set(0, 'end')
root = tkinter.Tk()
flb = FancyListbox(root, selectmode='multiple')
for n in range(10):
flb.insert('end', n)
flb.pack()
root.mainloop()
grab_release()
的使用在 an example on effbot 中观察到.
它对所有系统的影响可能并不相同。
关于python - tkinter 应用程序添加右键单击上下文菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014210/