当前位置: 首页 > news >正文

高级 Tkinter:使用类

一、说明

此文,我们将学习 Tkinter 中的类。如果您之前使用过Tkinter,您可能知道它有很多 GUI 功能可以用来创建应用程序。但是,在创建应用程序时,您很快就会意识到模块的功能远不止眼前所见。其中有很多隐藏的功能tkinter,其中之一就是在模块中使用类的方法。

二、设置 Tkinter 模块

不需要安装任何模块,因为该tkinter模块是标准 Python 库的一部分。但是,本文将讨论tkinter模块的稍微高级的形式,因此建议先阅读初学者系列。

我们需要导入tkinter模块:

# Importing the tkinter module
import tkinter as tk# Used for styling the GUI
from tkinter import tkk

三、在 Tkinter 中使用类

让我们了解如何在 Tkinter 中使用类。该应用程序的工作方式非常简单。我们首先创建一个根窗口,在其上放置一个框架。

为了使它看起来像一个具有不同窗口的应用程序,我们还将创建一个从一个框架切换到另一个框架的功能。

这会让用户产生一种错觉,以为自己被重定向到不同的窗口/选项卡,但实际上只是在框架之间切换。

我们将要使用的框架是MainPage、SidePage和CompletionScreen。我们将使用在它们之间切换的方法就是show_frame()方法。

四、编写代码

让我们创建一个基类,从该基类开始我们可以访问所有其他类/框架。

# Allowing us to extend from the Tk class
class testClass(tk.Tk):

通过从类中扩展,tk.Tk我们可以使用Tk()类中存在的组件。

4.1 初始化类

为了初始化类,我们使用__init__函数。这将创建一个方法,当我们从类中创建一个对象时,该方法将自行运行。
tk.Tk以类似的方式,我们也通过 init 初始化类。

import tkinter as tk
from tkinter import ttkclass windows(tk.Tk):def __init__(self, *args, **kwargs):tk.Tk.__init__(self, *args, **kwargs)# Adding a title to the windowself.wm_title("Test Application")# creating a frame and assigning it to containercontainer = tk.Frame(self, height=400, width=600)# specifying the region where the frame is packed in rootcontainer.pack(side="top", fill="both", expand=True)# configuring the location of the container using gridcontainer.grid_rowconfigure(0, weight=1)container.grid_columnconfigure(0, weight=1)# We will now create a dictionary of framesself.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] = frameframe.grid(row=0, column=0, sticky="nsew")# Using a method to switch framesself.show_frame(MainPage)

4.2. 创建切换视图框架的方法

现在我们已经创建了__init__并指定了要使用的框架,我们可以创建一个方法来切换我们正在查看的框架

def show_frame(self, cont):frame = self.frames[cont]# raises the current frame to the topframe.tkraise()

4.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 functionswitch_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模块中的类,为开发和创建新的应用程序打开了很多大门。
今天我们已经处理了相当多的代码,为了让我们达成共识,这里是要点!

http://www.xdnf.cn/news/1198513.html

相关文章:

  • 通过不同坐标系下的两个向量,求解旋转矩阵
  • 《C++ list 完全指南:list的模拟实现》
  • 《频率之光:维度回响》
  • mac电脑安装docker图文教程
  • 【笔记】活度系数推导
  • Linux驱动21 --- FFMPEG 音频 API
  • 深度解析 inaSpeechSegmenter:高效音频语音分割与检测开源工具
  • STL——list
  • Web Worker:解锁浏览器多线程,提升前端性能与体验
  • 【NLP舆情分析】基于python微博舆情分析可视化系统(flask+pandas+echarts) 视频教程 - 微博文章数据可视化分析-文章分类下拉框实现
  • PHP框架之Laravel框架教程:3. 数据库操作(简要)
  • Keil MDK 嵌入式开发问题:warning: #223-D: function “sprintf“ declared implicitly
  • Flutter开发实战之测试驱动开发
  • IP--MGER综合实验报告
  • 人工智能——图像梯度处理、边缘检测、绘制图像轮廓、凸包特征检测
  • 【MySQL篇】:MySQL基础了解以及库和表的相关操作
  • 2.苹果ios逆向-Windows电脑端环境搭建-Conda安装和使用(使用Conda来管理多个Python环境)
  • LeetCode第350题_两个数组的交集II
  • 图像处理:第二篇 —— 选择镜头的基础知识及对图像处理的影响
  • 代码随想录算法训练营二十八天|动态规划part01
  • ArkTS 模块通信全解析:用事件总线实现页面消息联动
  • LeetCode第349题_两个数组的交集
  • 【LeetCode】LRU 缓存 题解
  • MySQL 全详解:从入门到精通的实战指南
  • LeetCode 刷题【16. 最接近的三数之和、17. 电话号码的字母组合】
  • 【前端】【vscode】【.vscode/settings.json】为单个项目配置自动格式化和开发环境
  • 关系与逻辑运算 —— 寄存器操作的 “入门钥匙”
  • 分布式系统中Token续期问题解决方案
  • AIC 2025 热点解读:如何构建 AI 时代的“视频神经中枢”?
  • 四、搭建springCloudAlibaba2021.1版本分布式微服务-加入openFeign远程调用和sentinel流量控制