Tkinter-如何捕捉菜单栏子菜单按钮被按下



在下面的代码中,当选择菜单栏项Recipient/email/并选择地址时,我如何捕捉按下的电子邮件地址按钮?我已经找到了使用下拉菜单的例子,但我不知道如何应用下面的代码。

from tkinter import *
from tkinter import messagebox
class MenuBar(Menu):
def __init__(self, ws):
Menu.__init__(self, ws)
recipient= Menu(self, tearoff=0)
address = Menu(self, tearoff=0)
for email in ('joe@joe.com', 'sam@sam.com'):
address.add_command(label=email)
recipient.add_cascade(label='email', menu=address)
self.add_cascade(label='Recipient', menu=recipient)
class MenuTest(Tk):
def __init__(self):
Tk.__init__(self)
menubar = MenuBar(self)
self.config(menu=menubar)
if __name__ == "__main__":
ws=MenuTest()
ws.title('email recipient')
ws.geometry('400x300')
ws.mainloop()

您应该创建一个处理菜单选择并接受电子邮件字符串作为参数的方法

def __init__(self, ws):
# yadda yadda
for email in ('joe@joe.com', 'sam@sam.com'):
address.add_command(
label=email,
# add a command to call your selection handler
# using a lambda to pass 'email' as an argument
command: lambda e = email: self.on_selection(e)
)
def on_selection(self, email):  # this method will be fired on menu selection
print(email)  # do whatever you need to do with the selected email

最新更新