python3 + Gooey快速开发GUI应用程序
python3 + Gooey快速开发GUI应用程序
说明
- Gooey 是一个 Python GUI 程序开发框架,基于 wxPython GUI 库,其使用方法类似于 Python 内置 CLI 开发库 argparse,用一行代码即可快速将控制台程序转换为GUI应用程序。
安装
- 本文测试使用python 3.6.6 版本(python2请自行测试)
pip install Gooey
# 或者,您可以通过将项目克隆到本地目录来安装Gooey
git clone https://github.com/chriskiehl/Gooey.git
python setup.py install
示例
from gooey import Gooey, GooeyParser
@Gooey
def main():
parser = GooeyParser(description="My Cool GUI Program!")
parser.add_argument('Filename', widget="FileChooser") # 文件选择框
parser.add_argument('Date', widget="DateChooser") # 日期选择框
args = parser.parse_args() # 接收界面传递的参数
print(args)
if __name__ == '__main__':
main()
基本组件
控件名 | 控件类型 |
---|---|
FileChooser | 文件选择器 |
MultiFileChooser | 文件多选器 |
DirChooser | 目录选择器 |
MultiDirChooser | 目录多选器 |
FileSaver | 文件保存 |
DateChooser | 日期选择 |
TextField | 文本输入框 |
Dropdown | 下拉列表 |
Counter | 计数器 |
CheckBox | 复选框 |
RadioGroup | 单选框 |
全局配置
配置参数主要是对Gooey界面做全局配置,配置方法如下:
@Gooey(program_name='Demo')
def main():
...
和program_name参数配置一样,Gooey 还支持很多其它配置,下面是它支持的参数列表:
参数 | 类型 | 简介 |
---|---|---|
advanced | Boolean | 切换显示全部设置还是仅仅是简化版本 |
show_config | Boolean | Skips the configuration all together and runs the program immediately |
language | str | 指定从 gooey/languages 目录读取哪个语言包 |
program_name | str | GUI 窗口显示的程序名。默认会显 sys.argv[0]。 |
program_description | str | Settings 窗口顶栏显示的描述性文字。默认值从 ArgumentParser 中获取。 |
default_size | (600,400) | 窗口默认大小。 |
required_cols | 1 | 设置必选参数行数。 |
optional_cols | 2 | 设置可选参数行数。 |
dump_build_config | Boolean | 将设置以 JSON 格式保存在硬盘中以供编辑/重用。 |
richtext_controls | Boolean | 打开/关闭控制台对终端控制序列的支持(对字体粗细和颜色的有限支持) |
布局定制
通过使用一些简单的自定义,您可以使用Gooey实现相当灵活的布局。
在最高级别,您可以通过Gooey装饰器的各种参数来控制几个总体布局选项
show_sidebar=True
show_sidebar=False
navigation='TABBED'
tabbed_groups=True
示例
from gooey import Gooey, GooeyParser
from colored import stylize, attr, fg
@Gooey(
richtext_controls=True, # 打开终端对颜色支持
program_name="MQTT连接订阅小工具", # 程序名称
encoding="utf-8", # 设置编码格式,打包的时候遇到问题
progress_regex=r"^progress: (\d+)%$" # 正则,用于模式化运行时进度信息
)
def main():
settings_msg = 'MQTT device activation information subscription'
parser = GooeyParser(description=settings_msg)
subs = parser.add_subparsers(help='commands', dest='command')
my_cool_parser = subs.add_parser('MQTT消息订阅')
my_cool_parser.add_argument ("connect", metavar='运行环境',help="请选择开发环境",choices=['dev环境','staging环境'], default='dev环境')
my_cool_parser.add_argument ("device_type",metavar='设备类型',help="请选择设备类型",choices=['H1','H3'],default='H1')
my_cool_parser.add_argument ("serialNumber", metavar='设备SN号',default='LKVC19060047',help='多个请用逗号或空格隔开')
siege_parser = subs.add_parser('进度条控制')
siege_parser.add_argument('num',help='请输入数字',default=100)
args = parser.parse_args()
print(args,flush=True) # 坑点:flush=True在打包的时候会用到
# 将界面收集的参数进行处理
# ......
if __name__ == '__main__':
main()
将Gooey打包为独立应用程序
1、安装pyinstaller
pip install pyinstaller
2、创建build.spec
import gooey
gooey_root = os.path.dirname(gooey.__file__)
gooey_languages = Tree(os.path.join(gooey_root, 'languages'), prefix = 'gooey/languages')
gooey_images = Tree(os.path.join(gooey_root, 'images'), prefix = 'gooey/images')
a = Analysis(['gooey_test_v2.py'], # 项目文件名称
pathex=['D:\python3.6.6\Scripts'], # python安装路径
hiddenimports=[],
hookspath=None,
runtime_hooks=None,
)
pyz = PYZ(a.pure)
options = [('u', None, 'OPTION')]
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
options,
gooey_languages, # Add them in to collected files
gooey_images, # Same here.
name='CHANGE_MEe', # 打包文件名称
debug=False,
strip=None,
upx=True,
console=False,
icon=os.path.join(gooey_root, 'images', 'program_icon.ico'))
使用此规范,您只需要进行两个更改:
1、更新Analysis构造函数中的应用程序路径以指向您的Python脚本
2、将EXE构造函数中的name参数更新为程序的名称。
3、开始打包
最后一步是将规范文件提供给PyInstaller并使其发挥作用。
在目录中打开带有您的spec文件的终端,然后输入:
pyinstaller build.spec
eg:
'''
@author: Chris
Created on Dec 21, 2013
__ __ _
\ \ / / | |
\ \ /\ / /__| | ___ ___ _ __ ___ ___
\ \/ \/ / _ \ |/ __/ _ \| '_ ` _ \ / _ \
\ /\ / __/ | (_| (_) | | | | | | __/
___\/__\/ \___|_|\___\___/|_| |_| |_|\___|
|__ __|
| | ___
| |/ _ \
| | (_) |
_|_|\___/ _ _
/ ____| | | |
| | __ ___ ___ ___ _ _| | |
| | |_ |/ _ \ / _ \ / _ \ | | | | |
| |__| | (_) | (_) | __/ |_| |_|_|
\_____|\___/ \___/ \___|\__, (_|_)
__/ |
|___/
This demo will show you the full range of widget
types available to Gooey
'''
from gooey import Gooey, GooeyParser
# from message import display_message
@Gooey(dump_build_config=True, program_name="Widget Demo")
def main():
desc = "Example application to show Gooey's various widgets"
file_help_msg = "Name of the file you want to process"
my_cool_parser = GooeyParser(description=desc)
my_cool_parser.add_argument(
"FileChooser", help=file_help_msg, widget="FileChooser")
my_cool_parser.add_argument(
"DirectoryChooser", help=file_help_msg, widget="DirChooser")
my_cool_parser.add_argument(
"FileSaver", help=file_help_msg, widget="FileSaver")
my_cool_parser.add_argument(
"MultiFileChooser", nargs='*', help=file_help_msg, widget="MultiFileChooser")
my_cool_parser.add_argument("directory", help="Directory to store output")
my_cool_parser.add_argument('-d', '--duration', default=2,
type=int, help='Duration (in seconds) of the program output')
my_cool_parser.add_argument('-s', '--cron-schedule', type=int,
help='datetime when the cron should begin', widget='DateChooser')
my_cool_parser.add_argument('--cron-time',
help='datetime when the cron should begin', widget="TimeChooser")
my_cool_parser.add_argument(
"-c", "--showtime", action="store_true", help="display the countdown timer")
my_cool_parser.add_argument(
"-p", "--pause", action="store_true", help="Pause execution")
my_cool_parser.add_argument('-v', '--verbose', action='count')
my_cool_parser.add_argument(
"-o", "--overwrite", action="store_true", help="Overwrite output file (if present)")
my_cool_parser.add_argument(
'-r', '--recursive', choices=['yes', 'no'], help='Recurse into subfolders')
my_cool_parser.add_argument(
"-w", "--writelog", default="writelogs", help="Dump output to local file")
my_cool_parser.add_argument(
"-e", "--error", action="store_true", help="Stop process on error (default: No)")
verbosity = my_cool_parser.add_mutually_exclusive_group()
verbosity.add_argument('-t', '--verbozze', dest='verbose',
action="store_true", help="Show more details")
verbosity.add_argument('-q', '--quiet', dest='quiet',
action="store_true", help="Only output on error")
my_cool_parser.parse_args()
# display_message()
def here_is_more():
pass
if __name__ == '__main__':
main()
转自:https://blog.csdn.net/qq_33682575/article/details/103584885
不论你在什么时候开始,重要的是开始之后就不要停止。
不论你在什么时候结束,重要的是结束之后就不要悔恨。