[英]Menubar does not appear in tkinter when configured
I am creating an tkinter app.我正在创建一个 tkinter 应用程序。 For now I just want to get a very basic menubar to work, with a file section, and an exit button in the sub menu.现在我只想得到一个非常基本的菜单栏,它有一个文件部分,子菜单中有一个退出按钮。 Here is my object oriented code, which may be where I am going wrong:这是我的面向 object 的代码,这可能是我出错的地方:
import tkinter as tk
class MainApplication(tk.Frame):
def __init_(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.menubar = tk.Menu(self)
self.filemenu = tk.Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label="Exit", command=self.quit)
self.menubar.add_cascade(label="File", menu=self.filemenu)
self.config(menu=self.menubar)
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
However, this only creates a blank tkinter window.但是,这只会创建一个空白 tkinter window。 This usually works for me when I use procedural programming so I think I am doing something wrong with OOP.当我使用过程编程时,这通常对我有用,所以我认为我对 OOP 做错了什么。 I am trying to say self.config() as root.config(), but this does not work.我试图将 self.config() 称为 root.config(),但这不起作用。
2 big issues there.有2个大问题。 The first is that you misspelled __init__
, so none of your custom code is being run.首先是您拼错了__init__
,因此没有运行您的自定义代码。 The second is that you need to apply the menu to the root window, aka self.master (default name) or self.parent (your name).第二个是您需要将菜单应用于根 window,即 self.master(默认名称)或 self.parent(您的名称)。 Try like this:试试这样:
import tkinter as tk
class MainApplication(tk.Frame):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self.menubar = tk.Menu(self)
self.filemenu = tk.Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label="Exit", command=self.quit)
self.menubar.add_cascade(label="File", menu=self.filemenu)
self.master.config(menu=self.menubar)
if __name__ == "__main__":
root = tk.Tk()
root.geometry('200x200') # remove once you've added window content
win = MainApplication(root)
win.pack(side="top", fill="both", expand=True)
root.mainloop()
I also moved you to a python3 inheritance style, and defined a size so that you actually see something.我还将您移至 python3 inheritance 样式,并定义了一个大小,以便您实际看到一些东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.