首页 > 解决方案 > 更改 tkinter 命令的右键单击事件

问题描述

我想检测 tkinter Menu 命令上的右键单击事件。考虑下面的代码。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

menu_button = ttk.Menubutton(root, text="MENU")
menu_button.grid()

m = tk.Menu(menu_button, tearoff=False, activeborderwidth=0)
menu_button["menu"] = m # To avoid garbage collection

m.add_command(label="an option", command=lambda: print("option1"))
m.add_command(label="another option", command=lambda: print("option2"))

root.mainloop()

当我单击an optionoranother option时,命令按预期调用。但我想做的是捕捉右键单击事件。谁能知道我该如何检测它?

标签: pythontkintertkinter-menu

解决方案


使用button.bind("<Button-3>", event). 考虑这段代码:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

button = tk.Button(root, text='right click this')
button.pack()

button.bind("<Button-3>", lambda e: print('You right clicked'))

root.mainloop()

推荐阅读