编程学习网 > 编程语言 > Python > Python 教程:使用 Tkinter 的现代 GUI
2023
09-02

Python 教程:使用 Tkinter 的现代 GUI

Tkinter 是 Python 中创建桌面应用程序最广泛使用的库之一,许多开发者发现它易于使用,但主要问题是需要花费大量时间才能创建出漂亮的 GUI。我将向你展示如何在 Tkinter 中使用不多的代码创建漂亮的 GUI。

我将展示一个由Tom Schimansky创建的库的特性,它使您能够在Tkinter中创建漂亮的GUI,这样您就可以专注于后端编码而不是前端。
这是该库的链接,供以后学习使用:https://github.com/TomSchimansky/CustomTkinter
这是它们的官方文档链接:https://github.com/TomSchimansky/CustomTkinter/wiki
这是使用该库构建Tkinter应用程序前端的一些基本组件的快速演示。
Dark Theme
Light Theme
首先,您需要使用pip命令安装名为CustomTkinter的库
linuxmi@linuxmi:~/www.linuxmi.com$ pip install customtkinter

正如其官方文档所述:(由于CustomTkinter处于积极开发中,请尽可能经常更新库)
以下是一个非常基本的 Tkinter 应用程序:
# Importing Tkinter Library
from tkinter import *

# Creating Window of our App
root = Tk()

# Setting Widow width and Height
root.geometry('300x400')

# Creating a button widget
mybutton = Button(root, text='Hello World!www.linuxmi.com', font=("Inter", 14))

# showing at the center of the screen
mybutton.place(relx=0.5, rely=0.5, anchor=CENTER)

# Running the app
root.mainloop()

现在我们使用Custom Tkinter库,在我们以前的代码中进行以下更改:
# Importing Tkinter Library

from tkinter import *

import customtkinter
不再使用 Tkinter 创建根窗口,而是使用 Custom Tkinter 库创建它。
# Normal way to create Tkinter Window
# root = Tk()

# create CTk window
root = customtkinter.CTk()
使用 Custom Tkinter 创建按钮
# Use CTkButton instead of tkinter Button
button = customtkinter.CTkButton(master=root text="Hello world!")
唯一的区别在于通过指定master参数来定义的根窗口。
其余的代码保持不变
# showing at the center of the screen
button.place(relx=0.5, rely=0.5, anchor=CENTER)

# Running the app
root.mainloop()
这是完整的应用程序代码:
# Importing Libraries
from tkinter import *
import customtkinter

# create CTk window like you do with the Tk window
root = customtkinter.CTk()

# Setting Widow width and Height
root.geometry("500x600")

# Use CTkButton instead of tkinter Button
button = customtkinter.CTkButton(master=root, text="Hello World!www.linuxmi.com")

# showing at the center of the screen
button.place(relx=0.5, rely=0.5, anchor=CENTER)

# Running the app
root.mainloop()
这是输出

如果我们想要使用Tkinter来创建这个GUI,那么创建按钮和背景的样式将会花费大量的时间。但是使用custom Tkinter,我们几乎没有改变多少代码就能够在一分钟内创建这个漂亮的UI。
custom Tkinter的默认主题是系统定义的,也就是说,它会根据你当前在Windows或Mac上使用的主题来进行显示。如果你想指定你的应用程序的默认主题,可以在创建根窗口之前通过指定set_appearance_mode属性来实现:
set_appearance_mode有三个值:
System(使用用户操作系统的主题)
light(浅色主题)
dark(深色主题)
你可以通过指定set_default_color_theme属性来更改应用程序所有组件的颜色主题。
Custom Tkinter 提供了多种 Tkinter widget 的样式选择。
以下是 Custom Tkinter 支持的 widget:
CTkToplevel (additional windows)
CTkFrame
CTkScrollbar
CTkButton
CTkLabel
CTkEntry
CTkOptionMenu
CTkComboBox
CTkSwitch
CTkSlider
CTkProgressBar
CTkCheckBox
CTkRadioButton
CTkInputDialog
你可以在他们的代码库中查看一些例子。

以下是一个复杂例子的演示。

以上就是Python 教程:使用 Tkinter 的现代 GUI的详细内容,想要了解更多Python教程欢迎持续关注编程学习网。

扫码二维码 获取免费视频学习资料

Python编程学习

查 看2022高级编程视频教程免费获取