python进阶之GUI开发和构建exe程序

Owen Jia 2022年12月21日 523次浏览

GUI必学

作为辅助脚本语言的python,我的定位是工程java语言的补充,所以对于做一些小工具的语言进行学习,自然离不开GUI库掌握。

python3自带官方库 tkinter 已经算是小场景下的全面工具集。

tkinter

引用源码tkinter.init介绍

Tkinter provides classes which allow the display, positioning and
control of widgets. Toplevel widgets are Tk and Toplevel. Other
widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton,
Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox
LabelFrame and PanedWindow.

Properties of the widgets are specified with keyword arguments.
Keyword arguments have the same name as the corresponding resource
under Tk.

Widgets are positioned with one of the geometry managers Place, Pack
or Grid. These managers can be called with methods place, pack, grid
available in every Widget.

Actions are bound to events by resources (e.g. keyword argument
command) or with the method bind.

Example (Hello, World):
import tkinter
from tkinter.constants import *
tk = tkinter.Tk()
frame = tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
frame.pack(fill=BOTH,expand=1)
label = tkinter.Label(frame, text=“Hello, World”)
label.pack(fill=X, expand=1)
button = tkinter.Button(frame,text=“Exit”,command=tk.destroy)
button.pack(side=BOTTOM)
tk.mainloop()

tkinter的简单已用,超级吸引到我了。随便写了个交互界面,发现就十几行代码,这简直让人不可思议。真的是时代进步了,新语言已经解决了过去各种棘手问题。在java世界里,GWT Swing 包也可以写GUI程序,但总受制于java特性,太重。

有一种很普遍场景,在window或者mac下做一些小程序,用来处理一些数据或者文件文件转换,或者内容格式化等等。用python的GUI界面,用户只需要简单界面配置,然后“启动”按钮一点,等待一会就能完成目标。这样的小工具,对于很多不懂技术的人来说,牛上天了。

tkinter_demo

使用机制和Swing差不多,编程上看却简化太多,我只要一个py脚本即可完成小工具开发,真无论如何都是吸引人的。

可执行程序exe

python打包一个exe程序,居然也是如此便捷,让人乍舌。

pip install pyinstaller 安装 pyinstaller工具即可。

进入工程文件所在目录,直接pyinstaller src/app.py就会在当前目录下生成一个dist文件夹,里面有个app目录,这app目录里就是完成可执行程序。复制window电脑,进入目录里,找到exe后缀程序,直接双击运行。

tkinter_demo_exe

小技巧:将.py文件后缀改成.pyw,这样启动的程序即可隐藏控制台。

Python学习,快如闪电