主窗体类
使用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()

该博客介绍了如何使用tkinter库创建一个基础的主窗体类(Mainwindow),该类包含菜单栏、工具栏、状态栏和中心部件。作者提供了完整的代码实现,包括设置窗口的基本属性、创建菜单栏和状态栏显示消息的功能。通过继承Mainwindow类,开发者可以快速搭建具有标准组件的GUI应用。

8152

被折叠的 条评论
为什么被折叠?



