主窗体类
使用tkinter
实现GUI界面时, 经常需要添加菜单栏, 工具栏和状态栏, 我们可以实现一个主窗体类(Mainwindow
)来复用这部分功能.
主窗体类(Mainwindow
)包含一个菜单栏(menubar
), 一个工具栏(toolbar
), 一个状态栏(statusbar
)和一个中心部件(mainframe
).
以下是Mainwindow
类的实现代码, 以下代码可从我的github仓库中获得:
# mainwindow.py
class Mainwindow(Tk):
"""
Basic Mainwindow that contain a empty menubar, toolbar, statusbar
and mainframe.
"""
def __init__(self) -> None:
super().__init__()
# tool bar
self.toolbar = ttk.Frame(self, padding='3 3 3 3')
# mainframe.
# all widget need to add to mainframe,
# except menubar item, toolbar item and statusbar item
self.mainframe = ttk.Frame(self, padding='3 3 3 3')
# status bar
self.statusbar = ttk.Frame(self, padding='3 3 3 0')
self.toolbar.grid(column=0, row=0, sticky=NSEW)
self.mainframe.grid(column=0, row=1, sticky=NSEW)
self.statusbar.grid(column=0, row=2, sticky=NSEW)
self.option_add('*tearOff', FALSE)
# Create Menubar
win = self.winfo_toplevel()
self.menubar = Menu(win)
win['menu'] = self.menubar
self.statusmsg = StringVar()
self.statusLabel = Label(self.statusbar, textvariable=self.statusmsg)
self.statusLabel.grid(column=0, row=0, sticky=SW)
self.toolbar.rowconfigure(0, weight=1)
self.statusbar.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.columnconfigure(0, weight=1)
def showmessage(self, msg : str):
self.statusmsg.set(msg)
创建你自己的类并继承Mainwindow
即可.
# demo.py
from mainwindow import Mainwindow
class Window(Mainwindow):
def __init__(self) -> None:
super().__init__()
# set window's title.
self.title('Demo')
# set window's geometry size
self.geometry('600x400')
self.showmessage('Ready.')
if __name__ == '__main__':
w = Window()
w.mainloop()