介绍

PySimpleGUI是基于tkinter的封装,简化了tkinter的使用,从v5版本开始收费。我们可以选择使用基于v4版本的开源版本FreeSimpleGUI

安装

1
2
3
uv python pin 3.8 # 兼容win7的python版本
uv venv 
uv pip install FreeSimpleGUI

初体验

创建一个文本阅读器

python_YkKbPSDTcz

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import FreeSimpleGUI as sg

sg.set_options(dpi_awareness=True,font='Microsoft\ YaHei')

# Define the window's contents
layout = [
    [sg.Text('输入文件名:')],
    [
        sg.Input(key='file',expand_x=True),
     	sg.FileBrowse(button_text='选择文件',file_types=("Python & Text Files",	"*.py;*.txt")), sg.Button("确定",key='fileconfirm') ],
        [sg.Multiline(key='content',size=(None,5),expand_x=True,expand_y=True,disabled=True)]
]

# Create the window
window = sg.Window('文本阅读器', layout,resizable=True,size=(800,600))

# Display and interact with the Window using an Event Loop
while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED or event == 'quit':
        break

    if event == 'fileconfirm':
        file_path = values['file']
        try:
            f = open(file_path, encoding="utf-8")
            data = f.read()
            window['content'].update(data)
            f.close()
        except FileNotFoundError:
            sg.popup('文件不存在,请检查文件路径是否正确')
            
window.close()
  1. 我们使用sg.Text等组件去构建layout,layout是一个双重数组,第一层代表行数,第二层代表列数,正好对应tkinter的grid布局,默认靠左排列,可以通过sg.Window(element_justification='center')改为居中和tkinter默认布局保持一致。
  2. 每当有新事件触发时,window.read()会返回结果,一般是由某个组件引起的event,每个组件一般都绑定key属性,作为event名。比如在本例中,点击确认按钮会触发fileconfirm事件。
  3. window.read()将当前窗口所有的表单数据存放到values这个dict中,表单组件的Key即为dict的key。在本例中,通过values['file']获取到input的值。
  4. 每一个组件都可以通过window[key]去访问。在本例中,访问Multiline组件,通过window['content']去访问,并且通过window['content'].update('value')方法去设置表单组件值。
  5. sg.FileBrowse可以弹出文件选择框,默认该组件左边的Input作为文件路径显示,你也可以通过指定target的方式,绑定对应的Input。比如sg.FileBrowse(target='file'),绑定key为file的Input

打包

  1. 注意win7要使用python3.8的版本,并且保证升级到sp1版本,且安装KB2533623,否则打包后运行报错。ref
  2. 要安装pyinstaller==4.10配合python3.8打包。