高级的Tkinter:使用类 进行操作
今天我们将使用Tkinter中的类进行工作。如果你之前有使用过Tkinter,你可能知道有很多GUI功能可以用来创建应用程序。
但是在创建应用程序时,你很快意识到这个模块的复杂性远超出表面的看法。
tkinter中有很多隐藏的功能,其中一个是在模块中使用类的方法。
安装Tkinter模块
不需要安装任何模块,因为tkinter模块是Python标准库的一部分。
然而,本文将涉及稍微高级一点的tkinter模块,因此建议先阅读初级系列。
在你继续前进之前,不要忘记在这里阅读关于TKinter的基本教程。
- Tkinter Part – 1
- Tkinter Part – 2
- Tkinter Part – 3
如果你已经完成了基本的教程,让我们开始使用tkinter模块吧。
为了使用类,我们需要导入tkinter模块。
# Importing the tkinter module
import tkinter as tk
# Used for styling the GUI
from tkinter import tkk
为了使用方便,我们还将单独导入 ttk 包。
在Tkinter中使用类进行工作
让我们了解如何在Tkinter中使用类。应用程序的工作方式非常简单。
我们首先创建一个根窗口,在其上放置一个单独的框架。
为了让它看起来像一个带有不同窗口的应用程序,我们还将创建一个可以在不同框架之间切换的功能。
这让用户产生了一种错觉,觉得自己正在被重定向到一个不同的窗口/标签页,但实际上只是在不同的框架之间切换。
我们将使用的框架包括主页面、侧边页面和完成页面。
我们将使用show_frame()方法来在它们之间切换。
在编码上工作
让我们创建一个基类,从这个基类中我们可以访问所有其他的类/窗体来开始。
# Allowing us to extend from the Tk class
class testClass(tk.Tk):
从tk.Tk类扩展允许我们使用在Tk()类中存在的组件进行工作。
1. 类的初始化
为了初始化类,我们使用__init__函数。这样可以创建一个在我们从类中生成对象时自动运行的方法。
以类似的方式,我们也通过tk.Tk __init__ 初始化类。
import tkinter as tk
from tkinter import ttk
class windows(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# Adding a title to the window
self.wm_title("Test Application")
# creating a frame and assigning it to container
container = tk.Frame(self, height=400, width=600)
# specifying the region where the frame is packed in root
container.pack(side="top", fill="both", expand=True)
# configuring the location of the container using grid
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
# We will now create a dictionary of frames
self.frames = {}
# we'll create the frames themselves later but let's add the components to the dictionary.
for F in (MainPage, SidePage, CompletionScreen):
frame = F(container, self)
# the windows class acts as the root window for the frames.
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
# Using a method to switch frames
self.show_frame(MainPage)
2. 创建一种切换视图框架的方法。
现在我们已经创建了__init__,并指定了要使用的帧,我们可以创建一个方法来切换我们正在查看的帧。
def show_frame(self, cont):
frame = self.frames[cont]
# raises the current frame to the top
frame.tkraise()
3. 为框架创建多个类别。
现在,我们创建不同的类作为框架,通过show_frame()方法进行切换。
class MainPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Main Page")
label.pack(padx=10, pady=10)
# We use the switch_window_button in order to call the show_frame() method as a lambda function
switch_window_button = tk.Button(
self,
text="Go to the Side Page",
command=lambda: controller.show_frame(SidePage),
)
switch_window_button.pack(side="bottom", fill=tk.X)
class SidePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="This is the Side Page")
label.pack(padx=10, pady=10)
switch_window_button = tk.Button(
self,
text="Go to the Completion Screen",
command=lambda: controller.show_frame(CompletionScreen),
)
switch_window_button.pack(side="bottom", fill=tk.X)
class CompletionScreen(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Completion Screen, we did it!")
label.pack(padx=10, pady=10)
switch_window_button = ttk.Button(
self, text="Return to menu", command=lambda: controller.show_frame(MainPage)
)
switch_window_button.pack(side="bottom", fill=tk.X)
如果你注意到了的话,这些类是通过 self.frames 变量添加到主类中的。
我将保留将类实现的命令放在__name__==”main”中,但你也可以直接使用它。
if __name__ == "__main__":
testObj = windows()
testObj.mainloop()
继续前进
我们现在已经完成了定义类和方法的步骤,可以运行这个脚本了。
这应该给你提供了一个小窗口,只需点击一个按钮即可在帧之间进行切换。
在更高的级别上,你甚至可以在应用程序顶部的菜单栏中切换框架的功能。
结论
在使用tkinter模块中与类一起工作,打开了许多可以处理和创建新应用程序的机会。
我们今天处理了相当多的代码,为了确保我们都理解一致,这是核心要点!
如果你希望查看一个现成的例子,请看看我的项目“艾森票务”,它实现了许多Tkinter的特性,包括类,并且使用SQLite3运行。
参考资料
- Tkinter Documentation
- Tkinter Classes