如何基于python编写GUI并打包发布

目录
1 准备工作
python是一定要安装的,参考anaconda安装这一部分,另外强烈建议单独起一个conda环境,参考python环境管理,比如命令行输入:
conda create -n python-gui python=3.9实测纯净环境pyinstaller打包输出的文件大小更加可控,然后激活环境后安装两个必须的依赖,有其他依赖也记得安装:
# conda activate python-gui
# 必须依赖安装
pip install pysimplegui pyinstaller
# 额外依赖安装
pip install requests2 编写GUI示例
此处参考了以下几个链接中的教程:
https://github.com/PySimpleGUI/PySimpleGUI
https://github.com/pyinstaller/pyinstaller
https://realpython.com/pysimplegui-python/#packaging-your-pysimplegui-application-for-windows
python的样例代码是:
import PySimpleGUI as sg
# Define the window's contents
layout = [[sg.Text("What's your name?")],
[sg.Input(key='-INPUT-')],
[sg.Text(size=(40,1), key='-OUTPUT-')],
[sg.Button('Ok'), sg.Button('Quit')]]
# Create the window
window = sg.Window('Window Title', layout)
# Display and interact with the Window using an Event Loop
while True:
event, values = window.read()
# See if user wants to quit or window was closed
if event == sg.WINDOW_CLOSED or event == 'Quit':
break
# Output a message to the window
window['-OUTPUT-'].update('Hello ' + values['-INPUT-'] + "! Thanks for trying PySimpleGUI")
# Finish up by removing from the screen
window.close()假设我保存为文件test_gui.py,打开终端激活conda环境后执行:
# conda activate python-gui
python test_gui.py此时已经可以看到GUI窗口了,效果如图:
python执行GUI示例
点击也可以正常执行:
3 发布GUI示例
此处只示例windows打包,打开终端激活conda环境后执行:
# conda activate python-gui
pyinstaller --noconsole --onefile test_gui.py如果不新起conda环境,这里打包出来的exe文件可能会巨大,得到的可执行文件可下载查看test_gui.exe,这样就完成了GUI的简单发布