首先,我们需要安装PySimpleGUI:
# 使用pip安装PySimpleGUI# pip install PySimpleGUI
PySimpleGUI的核心概念非常简单:
窗口(Window):所有界面元素的容器布局(Layout):决定各个元素如何排列事件循环(Event Loop):处理用户的操作2. 创建第一个窗口来看看最基础的PySimpleGUI程序:
import PySimpleGUI as sg# 创建窗口布局layout = [ [sg.Text('你好!这是我的第一个PySimpleGUI程序')], [sg.Button('确定')]]# 创建窗口window = sg.Window('我的第一个窗口', layout)# 事件循环while True: event, values = window.read() if event == sg.WIN_CLOSED or event == '确定': breakwindow.close()
3. 制作一个简单的登录界面让我们来做点实用的!
import PySimpleGUI as sgdef create_login_window(): layout = [ [sg.Text('用户名:'), sg.Input(key='-USERNAME-')], [sg.Text('密码: '), sg.Input(key='-PASSWORD-', password_char='*')], [sg.Button('登录'), sg.Button('取消')] ] return sg.Window('登录界面', layout)window = create_login_window()while True: event, values = window.read() if event == sg.WIN_CLOSED or event == '取消': break if event == '登录': username = values['-USERNAME-'] password = values['-PASSWORD-'] if username == 'admin' and password == '123456': sg.popup('登录成功!') break else: sg.popup('用户名或密码错误!')window.close()
📌 小贴士:使用key参数给元素添加标识符,可以更方便地获取元素的值!
4. 创建一个简单的计算器来做个更有趣的应用:
import PySimpleGUI as sgdef create_calculator(): layout = [ [sg.Input(key='-DISPLAY-', size=(20, 1), justification='right')], [sg.Button('7'), sg.Button('8'), sg.Button('9'), sg.Button('/')], [sg.Button('4'), sg.Button('5'), sg.Button('6'), sg.Button('*')], [sg.Button('1'), sg.Button('2'), sg.Button('3'), sg.Button('-')], [sg.Button('0'), sg.Button('.'), sg.Button('='), sg.Button('+')], [sg.Button('清除')] ] return sg.Window('简易计算器', layout)window = create_calculator()current_num = ''while True: event, values = window.read() if event == sg.WIN_CLOSED: break if event in '0123456789.': current_num += event window['-DISPLAY-'].update(current_num) if event in '+-*/': current_num += event window['-DISPLAY-'].update(current_num) if event == '=': try: result = eval(current_num) window['-DISPLAY-'].update(result) current_num = str(result) except: window['-DISPLAY-'].update('错误') current_num = '' if event == '清除': current_num = '' window['-DISPLAY-'].update('')window.close()
实用技巧:
使用sg.theme()可以改变界面主题,比如sg.theme('DarkBlue3')通过size参数调整元素大小justification参数可以设置文本对齐方式5. 常用控件一览PySimpleGUI提供了丰富的控件:
import PySimpleGUI as sglayout = [ [sg.Text('基础控件展示')], [sg.Input(key='-INPUT-')], [sg.Combo(['选项1', '选项2', '选项3'], key='-COMBO-')], [sg.Slider(range=(0, 100), orientation='h', key='-SLIDER-')], [sg.Checkbox('复选框', key='-CHECK-')], [sg.Radio('单选1', 'RADIO1'), sg.Radio('单选2', 'RADIO1')], [sg.Multiline(size=(30, 5), key='-MULTI-')], [sg.Button('确定'), sg.Button('取消')]]window = sg.Window('控件展示', layout)
📌 小贴士:布局使用嵌套列表,每个子列表代表一行,非常直观!
今天的Python学习之旅就到这里啦!记得动手敲代码,尝试创建自己的GUI程序。祝大家学习愉快,Python学习节节高!