子类化tkinter.Menu产生默认菜单 [英] Subclassing tkinter.Menu results in default menus
问题描述
我正在尝试创建一个tkinter GUI应用程序,同时将我的代码组织到主要应用程序,框架和菜单的类中.对于菜单,我将其归类为tkinter.menu,但它为我提供了一堆默认菜单,但不包括我创建的菜单和命令.我已尽力将其简化为以下说明该问题的工作示例:
I'm trying to create a tkinter GUI application while organizing my code into classes for the main application, the frame, and the menu. For the menu, I'm subclassing tkinter.menu, but it's giving me a bunch of default menus and not including the menus and commands I've created. I've stripped it down as best I can to the following working example that illustrates the problem:
首先,我将tkinter.TK子类化以创建主窗口小部件,其中包含主窗口和菜单.为了说明起见,我在文件"菜单中添加了一个空方法作为命令添加.接下来,我将tkinter.Frame子类化以创建主框架.为了说明,我在框架中添加了一个文本框.最后,我将tkinter.Menu子类化以创建主菜单,并添加了子菜单"File"和命令"Open".
First I subclassed tkinter.TK to create the main widget, containing the main window and the menu. For illustration, I included one empty method to add as a command in the File menu. Next, I subclassed tkinter.Frame to create the main frame. For illustration, I added a text box to the frame. Finally, I subclassed tkinter.Menu to create the main menu and added the submenu "File" and a command "Open".
import tkinter
class Application(tkinter.Tk):
def __init__(self):
tkinter.Tk.__init__(self)
self.main = MainWindow(master=self)
self.menu = MainMenu(master=self)
self.main.pack(fill=tkinter.BOTH, expand=True)
def open(self):
pass
class MainWindow(tkinter.Frame):
def __init__(self, master):
tkinter.Frame.__init__(self)
self.master = master
self.textbox = tkinter.Text()
self.textbox.pack(fill=tkinter.BOTH, expand=True)
class MainMenu(tkinter.Menu):
def __init__(self, master=None):
tkinter.Menu.__init__(self, master=None)
self.master = master
self.file = tkinter.Menu(self)
self.add_cascade(label="File", menu=self.file)
self.file.add_command(label="Open", command=master.open)
if __name__ == "__main__":
Application().mainloop()
结果是一堆我没有创建的菜单,包括没有我的打开"命令的文件"菜单:
The result is a bunch of menus I didn't create, including a File menu without my "Open" command:
我要去哪里错了?
推荐答案
替换:
self.menu = MainMenu(master=self)
具有:
self['menu'] = MainMenu(master=self)
# or self["menu"] = MainMenu(master=self)
# or self.config(menu=MainMenu(master=self))
# or self.configure(menu=MainMenu(master=self))
或添加:
self['menu'] = self.menu
# or self["menu"] = self.menu
# or self.config(menu=self.menu)
# or self.configure(menu=self.menu)
之后的任何地方:
self.menu = ...
将菜单作为 the 菜单分配给类似Toplevel
的小部件.
to have your menu assigned as the menu to your Toplevel
-like widget.
这篇关于子类化tkinter.Menu产生默认菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!