我正在尝试使用Tkinter在Python中编写一个带有菜单栏的简单OOP窗口。我可以完成我想要的程序编程,但我遇到了试图将它包装在类中的打嗝。这是一个小小的嗤之以鼻:
from Tkinter import *
class App(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Example")
self.pack(fill=BOTH, expand = 1)
""" Menu Bar """
self.menubar = Menu(self)
self.filemenu = Menu(self.menubar, tearoff=0)
self.filemenu.add_command(label = "Open", command = None)
self.filemenu.add_command(label = "Save", command = None)
self.filemenu.add_command(label = "Save As", command = None)
self.filemenu.add_command(label = "Close", command = None)
self.filemenu.add_separator()
self.filemenu.add_command(label = "Exit", command = None)
self.menubar.add_cascade(label = 'File', menu = self.filemenu)
self.config(menu = self.menubar)
def main():
root = Tk()
root.geometry("800x600+300+300")
app = App(root)
root.mainloop()
if __name__ == '__main__':
main()
当我运行时,我收到此错误:
Traceback (most recent call last):
File "C:/Users/xx/PycharmProjects/GUIS/layout.py", line 39, in <module>
main()
File "C:/Users/xx/PycharmProjects/GUIS/layout.py", line 35, in main
app = App(root)
File "C:/Users/xx/PycharmProjects/GUIS/layout.py", line 8, in __init__
self.initUI()
File "C:/Users/xx/PycharmProjects/GUIS/layout.py", line 28, in initUI
self.config(menu = self.menubar)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1262, in configure
return self._configure('configure', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1253, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown option "-menu"
任何人都在关心帮助一个菜鸟吗?
答案 0 :(得分:1)
在TKinter中,您应该将菜单栏添加到根目录,因为它应该在任何顶层窗口上。 即在这种情况下,
self.parent.config(menu = self.menubar)