Tkinter GUI中的类菜单
我正在做一个图形用户界面(Gui),我想知道是否可以把窗口的菜单属性放到我脚本的一个单独的类里,这样代码会更清晰,也更容易改进。
我现在的代码是:
class Application(Frame):
""" main window application """
def __init__(self, boss = None):
(...)
self.menu = Menu(self)
self.master.config(menu = self.menu)
self.select = Menu(self.menu)
self.menu.add_cascade(label = 'Select', menu = self.select)
self.select.add_command(label = 'Select all', command = self.select_all)
...
我希望能像这样:
class MenuBar:
# all the content of the menu here
class Application(Frame):
(...)
self.menu = MenuBar(self) ?
祝好,
1 个回答
16
是的,这是可能的:
import tkinter as tk
# import Tkinter as tk # if using python 2
import sys
class MenuBar(tk.Menu):
def __init__(self, parent):
super().__init__(parent)
fileMenu = tk.Menu(self, tearoff=False)
self.add_cascade(label="File",underline=0, menu=fileMenu)
fileMenu.add_command(label="Exit", underline=1, command=self.quit)
def quit(self):
sys.exit(0)
class App(tk.Tk):
def __init__(self):
super().__init__()
menubar = MenuBar(self)
self.config(menu=menubar)
if __name__ == "__main__":
app=App()
app.mainloop()