超级实用 Python GUI 入门 python做gui用什么好
off999 2024-12-18 16:12 36 浏览 0 评论
有时候使用 python 做自动化运维操作,开发一个简单的应用程序非常方便。程序写好,每次都要通过命令行运行 python 程序,就不是那么人性化了。为了更方便的操作,使用 Python GUI 编写界面程序,方便后续程序的操作。
本文基于:Tkinter 进行讲解从安装到打包,一站式完成一个应用打包。
安装 python 和 Tkinter
下载 python,一般情况下 Tkinter 也是随 python 一起下载的,如果没有使用单独安装一下。在目前的 python 版本中,windows 环境一般自带了 pip(包管理工具) 和 Tkinter, 其他的系统如果没有可以手动安装。
Tkinter
Tkinter 是 Python 的标准 GUI 库,使用它可以创建跨平台的桌面应用程序。
我们要开发一个桌面的 GUI,其实可以简单的分为以下几个内容:窗口、页面布局、控件、事件处理和其他的高级内容。
导入包
import tkinter as tk
from tkinter import ttk五、Tkinter 窗口
root = tk.Tk()
root.title("Tkinter Demo")
root.geometry("400x300")
root.configure(bg="lightblue") root.resizable(True, True)
root.attributes('-alpha', 0.95) root.bind("<KeyPress>", on_key_press)
# Run the application
root.mainloop()执行 mainloop 方法,窗口才能运行,其实就是一直在循环的绘制页面,没有调用就绘制不出来。tk 上具有 Tk 方法创建一个窗口,框口的叫法:自己定,一般是 root 或者 window。
窗口上我们设置:
属性/方法 | 描述 | 示例 |
title() | 设置窗口的标题 | root.title("My Application") |
geometry() | 设置窗口的初始大小和位置 | root.geometry("400x300") |
resizable() | 控制窗口是否可以调整大小 | root.resizable(False, False) |
configure() | 设置窗口的其他属性,如背景颜色 | root.configure(bg="lightblue") |
iconbitmap() | 设置窗口的图标(仅适用于 Windows) | root.iconbitmap('path_to_icon.ico') |
state() | 设置窗口的状态,如最小化、最大化或正常 | root.state('zoomed') |
attributes() | 设置窗口的各种属性,如透明度、置顶等 | root.attributes('-alpha', 0.9) |
mainloop() | 启动 Tkinter 的主事件循环 | root.mainloop() |
quit() | 退出主事件循环,关闭应用程序 | root.quit() |
以下是运行结果:一个没有任何内容的程序
Tkinter 布局
做过 UI 开发都知道,布局是开始应用程序的重要部分,那么 Tkinter 是如何布局的呢?
Tkinter 布局通常是三种方式:pack、grid、place。
- pack 顺序排列
import tkinter as tk
root = tk.Tk()
root.title("Pack Layout Example")
root.geometry("400x300")
root.configure(bg="lightblue")
root.resizable(True, True)
root.attributes('-alpha', 0.95)
button1 = tk.Button(root, text="按钮 top")
button2 = tk.Button(root, text="按钮 left")
button3 = tk.Button(root, text="按钮 right")
button1.pack(side="top", fill="x")
button2.pack(side="left", expand=True)
button3.pack(side="right", fill="y")
root.mainloop()三个按钮,上下布局,下面部分是左右布局,并且左边是自动扩展内容大小,效果图如下:
import tkinter as tk
root = tk.Tk()
root.title("Pack Layout Example")
root.geometry("400x300")
root.configure(bg="lightblue")
root.resizable(True, True)
root.attributes('-alpha', 0.95)
button1 = tk.Button(root, text="按钮 top")
button2 = tk.Button(root, text="按钮 left")
button3 = tk.Button(root, text="按钮 right")
button1.pack(side="top", fill="x")
button2.pack(side="left", expand=True)
button3.pack(side="right", fill="y")
root.mainloop()- grid 网格布局
import tkinter as tk
root = tk.Tk()
root.title("Pack Layout Example")
root.geometry("400x300")
root.configure(bg="lightblue")
root.resizable(True, True)
root.attributes('-alpha', 0.95)
label1 = tk.Label(root, text="Label 1")
label2 = tk.Label(root, text="Label 2")
label3 = tk.Label(root, text="Label 3")
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
entry3 = tk.Entry(root)
label1.grid(row=0, column=0, padx=10, pady=10)
entry1.grid(row=0, column=1, padx=10, pady=10)
label2.grid(row=0, column=2, padx=10, pady=10)
entry2.grid(row=0, column=3, padx=10, pady=10)
label3.grid(row=1, column=0, padx=10, pady=10)
entry3.grid(row=1, column=1, padx=10, pady=10)
root.mainloop()网格布局的使用太常见的,支持网格布局是非常重要的。
- place 定位布局
place 通常用于设置控件位置
import tkinter as tk
root = tk.Tk()
root.title("place Layout Example")
root.geometry("400x300")
root.configure(bg="lightblue")
root.resizable(True, True)
root.attributes('-alpha', 0.95)
label = tk.Label(root, text="This is a label")
button = tk.Button(root, text="This is a button")
label.place(x=50, y=50)
button.place(relx=0.5, rely=0.5, anchor="center")
root.mainloop()了解了布局的基本情况了,下面就该熟悉控件了。空间就是窗口中的元素。
Tkinter 控件
- 常用控件
控制是 UI 开发的重要部分,有了这些控件我们就能快速的开发符合需求的交互效果,那么 Tkinter 支持哪些控件呢?以下是 Thinter 常用的空间:
- Label: 静态文本
- Button: 触发事件的按钮
- Entry:当行文本框
- Listbox:列表(包含事件)
- Checkbutton:复选框(包含状态)
- Radiobutton:单选按钮(包含状态)
- Menu:菜单(文件,退出)
- Scrollbar: 滚动条
- Canvas:canvas 绘图
- Notebook:标签页控件
这里以菜单给出一个示例:
def on_menu_click():
label.config(text="Menu item clicked")
file_menu = tk.Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Open", command=on_menu_click)
file_menu.add_command(label="Save", command=on_menu_click)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.quit)创建菜单也很简单,添加级联内容,添加命令和分隔符,使用 command 绑定一个事件,菜单的功能就完成了。
- 自定义控件样式
- 定义样式数据
button = tk.Button(root, text="Click Me", bg="blue", fg="white", font=("Helvetica", 12))
button.pack(padx=20, pady=10)在 Button 控件上使用 bg/fg 定义前景和背景色。使用 pack 布局定义 padding 的 x/y 两个方向。
- 使用 theme 统一主题
button = tk.Button(root, text="Click Me", bg="blue", fg="white", font=("Helvetica", 12))
button.pack(padx=20, pady=10)- 自定义控件样式
通过 style 控制 button 控件的自定义样式:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Custom Styled Button")
style = ttk.Style()
style.configure('Custom.TButton', foreground='blue', font=('Helvetica', 14, 'bold'), padding=10)
button = ttk.Button(root, text="Custom Button", style='Custom.TButton')与统一主题不同的是:在空间上使用 style 属性指向自定义样式名称,此处是 Custom.TButton
Tkinter 事件交互
当我们有了控件,我们就需要绑定时间,完成 UI 中的基本交互行为,这些事件其实也很简单就是函数
- Tkinter 变量
var = tk.IntVar() # 整数
if var.get() == 1: # 访问
// handler
var.set(0) # 设置
double_var = tk.DoubleVar()
check_var = tk.BooleanVar() # boolean
radio_var = tk.StringVar() # 字符串, 通常与 Label 一起使用
listbox = tk.Listbox(root) # 列表Tkinter 变量也是常用件的数据类型,用于不同的控件。
- 点击事件
def on_button_click():
button.config(text="Button Clicked!")
button = tk.Button(root, text="Click Me", command=on_button_click)
button.pack(pady=10)点击事件通过 command 绑定 py 函数,此处使用 button 的 config 方法设置按钮的文字。
- 文本框输入
import tkinter as tk
root = tk.Tk()
root.title("文本数据提交数据")
root.geometry("400x300")
root.configure(bg="lightblue")
root.resizable(True, True)
root.attributes('-alpha', 0.95)
def on_submit():
text = entry.get()
label.config(text=f"You typed: {text}")
entry = tk.Entry(root, width=30)
entry.pack(pady=20)
button = tk.Button(root, text="Submit", command=on_submit)
button.pack()
label = tk.Label(root, text="Type something and click Submit")
label.pack(pady=20)
root.mainloop()定义三个元素:entry 输出文本内容,button 绑定提交数据,提交时获取 entry 的数据(get 方法),label 中函数提交的数据。这样就完成一个基本的数据流操作。其他的不再复述了。
原生的 TkinterUI 不够漂亮,可能是不少开发者劝退的原因,下面我们对界面美化进行探索。
Tkinter 扩展
customtkinter 是一个基于 Tkinter 的现代且可定制的 Python UI 库。
- CustomTkinter 官方代码托管仓库
- CustomTkinter Doc 文档地址
我们给出一个示例:
- 安装
pip3 install customtkinter- 示例
import customtkinter
customtkinter.set_appearance_mode("System") # Modes: system (default), light, dark
customtkinter.set_default_color_theme("blue") # Themes: blue (default), dark-blue, green
app = customtkinter.CTk() # create CTk window like you do with the Tk window
app.geometry("400x240")
def button_function():
print("button pressed", entry.get())
button = customtkinter.CTkButton(master=app, text="提交", command=button_function)
button.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER)
label = customtkinter.CTkLabel(master=app, text="label")
label.place(relx=0.5, rely=0.1, anchor=customtkinter.CENTER)
entry = customtkinter.CTkEntry(master=app,)
entry.place(relx=0.5, rely=0.3, anchor=customtkinter.CENTER)
app.mainloop()基于 customtkinter 实现一个简单的界面,按钮是不是好看多了。但是代码的初始化方式也发生了变化。
打包
当我们有一个可以执行的 python 后,我们不想每次都去运行一下,这个时候我们就需要打包了,python 的打包工具也不少这里就推荐使用 PyInstaller
- pyinstaller 官方文档
- pyinstaller 代码托管地址
pip install -U pyinstaller打包:
pyinstaller --onefile --windowed your_entry_program_file.py- --onefile:将所有内容打包成一个可执行文件。
- --windowed:在Windows上生成一个不带控制台窗口的GUI应用程序。
打包完毕之后会生成一些列文件, 可执行文件就在 dist 目录小。
build/
dist/ # 目标文件文职
- xxx.exe(windows)
...安装器
PyInstaller 构架出了可执行文件,但是没有安装器,我们可是配合一些工具完成安装过程:
- Inno Setup:免费的Windows安装程序制作工具,提供强大的脚本语言来定义安装过程。
- NSIS :跨平台的安装制作工具,可创建复杂的安装程序和解决方案。
小结
本文从主旨在讲解 Python GUI 入门,从 Tkinter 构建 UI 到 UI 库 customtkinter 的使用,最后到应用程序打包和安装器推荐,希望这些对读者有帮助。
作者:编程杂货铺
链接:https://juejin.cn/post/7386476988879683624
相关推荐
- 安全教育登录入口平台(安全教育登录入口平台官网)
-
122交通安全教育怎么登录:122交通网的注册方法是首先登录网址http://www.122.cn/,接着打开网页后,点击右上角的“个人登录”;其次进入邮箱注册,然后进入到注册页面,输入相关信息即可完...
- 大鱼吃小鱼经典版(大鱼吃小鱼经典版(经典版)官方版)
-
大鱼吃小鱼小鱼吃虾是于谦跟郭麒麟的《我的棒儿呢?》郭德纲说于思洋郭麒麟作诗的相声,最后郭麒麟做了一首,师傅躺在师母身上大鱼吃小鱼小鱼吃虾虾吃水水落石出师傅压师娘师娘压床床压地地动山摇。...
-
- 哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)
-
要想将ppt免费转换为pdf的话,我们建议大家可以下一个那个wps,如果你是会员的话,可以注册为会员,这样的话,在wps里面的话,就可以免费将ppt呢转换为pdfpdf之后呢,我们就可以直接使用,不需要去直接不需要去另外保存,为什么格式转...
-
2026-02-04 09:03 off999
- 电信宽带测速官网入口(电信宽带测速官网入口app)
-
这个网站看看http://www.swok.cn/pcindex.jsp1.登录中国电信网上营业厅,宽带光纤,贴心服务,宽带测速2.下载第三方软件,如360等。进行在线测速进行宽带测速时,尽...
- 植物大战僵尸95版手机下载(植物大战僵尸95 版下载)
-
1可以在应用商店或者游戏平台上下载植物大战僵尸95版手机游戏。2下载教程:打开应用商店或者游戏平台,搜索“植物大战僵尸95版”,找到游戏后点击下载按钮,等待下载完成即可安装并开始游戏。3注意:确...
- 免费下载ppt成品的网站(ppt成品免费下载的网站有哪些)
-
1、Chuangkit(chuangkit.com)直达地址:chuangkit.com2、Woodo幻灯片(woodo.cn)直达链接:woodo.cn3、OfficePlus(officeplu...
- 2025世界杯赛程表(2025世界杯在哪个国家)
-
2022年卡塔尔世界杯赛程公布,全部比赛在卡塔尔境内8座球场举行,2022年,决赛阶段球队全部确定。揭幕战于当地时间11月20日19时进行,由东道主卡塔尔对阵厄瓜多尔,决赛于当地时间12月18日...
- 下载搜狐视频电视剧(搜狐电视剧下载安装)
-
搜狐视频APP下载好的视频想要导出到手机相册里方法如下1、打开手机搜狐视频软件,进入搜狐视频后我们点击右上角的“查找”,找到自已喜欢的视频。2、在“浏览器页面搜索”窗口中,输入要下载的视频的名称,然后...
- 永久免费听歌网站(丫丫音乐网)
-
可以到《我爱音乐网》《好听音乐网》《一听音乐网》《YYMP3音乐网》还可以到《九天音乐网》永久免费听歌软件有酷狗音乐和天猫精灵,以前要跳舞经常要下载舞曲,我从QQ上找不到舞曲下载就从酷狗音乐上找,大多...
- 音乐格式转换mp3软件(音乐格式转换器免费版)
-
有两种方法:方法一在手机上操作:1、进入手机中的文件管理。2、在其中选择“音乐”,将显示出手机中的全部音乐。3、点击“全选”,选中所有音乐文件。4、点击屏幕右下方的省略号图标,在弹出菜单中选择“...
- 电子书txt下载(免费的最全的小说阅读器)
-
1.Z-library里面收录了近千万本电子书籍,需求量大。2.苦瓜书盘没有广告,不需要账号注册,使用起来非常简单,直接搜索预览下载即可。3.鸠摩搜书整体风格简洁清晰,书籍资源丰富。4.亚马逊图书书籍...
- 最好免费观看高清电影(播放免费的最好看的电影)
-
在目前的网上选择中,IMDb(互联网电影数据库)被认为是最全的电影网站之一。这个网站提供了各种类型的电影和电视节目的海量信息,包括剧情介绍、演员表、评价、评论等。其还提供了有关电影制作背后的详细信息,...
- 孤单枪手2简体中文版(孤单枪手2简体中文版官方下载)
-
要将《孤胆枪手2》游戏的征兵秘籍切换为中文,您可以按照以下步骤进行操作:首先,打开游戏设置选项,通常可以在游戏主菜单或游戏内部找到。然后,寻找语言选项或界面选项,点击进入。在语言选项中,选择中文作为游...
欢迎 你 发表评论:
- 一周热门
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
