Python Tkinter - Virtual Event <<MenuSelect>>不起作用?

Python Tkinter - Virtual Event <<MenuSelect>> not working?

提问人:renehahn 提问时间:9/9/2023 最后编辑:renehahn 更新时间:9/10/2023 访问量:47

问:

在我的 tkinter 代码中,见下文,我尝试利用虚拟事件将简单的消息打印到控制台。<<MenuSelect>>

from tkinter import Tk, Menu, N, W, E, S, DISABLED
from tkinter import ttk


class App(Tk):
    def __init__(self):
        super().__init__()
        self.title('Contacts App')
        self.geometry('500x350')
        self.mainframe = ttk.Frame(self)
        self.mainframe.grid(row=0, column=0, sticky=(
            N, W, E, S), padx=10, pady=10)
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.statusbar = StatusBar()
        self.statusbar.grid(row=1, column=0, sticky=(W, E))
        self.menubar = MenuBar()
        self.config(menu=self.menubar)


class MenuBar(Menu):
    def __init__(self):
        super().__init__()
        # Start Menu
        self.menu_start = Menu(self, tearoff=0)
        self.menu_start.add_command(
            label="New Contact", command=self.create_contact, accelerator='Ctrl+C')
        self.menu_start.add_command(
            label="New Account", command=self.create_account, accelerator='Ctrl+A')
        self.menu_start.add_separator()
        self.menu_start.add_command(
            label="Settings", command=self.open_settings)
        self.menu_start.entryconfigure('Settings', state=DISABLED)
        self.menu_start.add_separator()
        self.menu_start.add_command(label="Exit", command=self.quit)
        self.add_cascade(menu=self.menu_start, label="Start")

        # Virtual Event not working
        self.menu_start.bind('<<MenuSelect>>', lambda event: print(
            f'Menu item {event.widget.index("active")}'))

    def create_contact(self):
        pass

    def create_account(self):
        pass

    def open_settings(self):
        pass


class StatusBar(ttk.Frame):
    def __init__(self):
        super().__init__()
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.status_label = ttk.Label(
            self, borderwidth=1, anchor='w', padding="0 0 3 0",
            relief='solid', background='#cbd2db', foreground='#302f35')
        self.status_label.grid(row=1, column=0, sticky=(W, E))

    def set(self, text):
        self.status_label['text'] = text
        self.status_label.update_idletasks()

    def clear(self):
        self.status_label['text'] = ''
        self.status_label.update_idletasks()


if __name__ == '__main__':
    App().mainloop()

在下一次迭代中,当用户将鼠标移到菜单项上时,我希望在状态栏上显示文本信息(类似于此处。但是,这似乎根本行不通。我没有看到任何控制台输出。有什么建议吗?<<MenuSelect>>

Python tkinter 事件 菜单 鼠标

评论

0赞 Derek 9/10/2023
此链接可能会有所帮助。stackoverflow.com/questions/33132486/......
0赞 renehahn 9/13/2023
谢谢@Derek,但它仍然不起作用。我正在使用 Windows 10 和 Python 3.11.4。我也在运行 Linux/Python 3.11.4 的兄弟机器上尝试过,但没有成功。

答: 暂无答案