PySimpleGUIPython GUI 工具包

联合创作 · 2023-09-28 06:14

PySimpleGUI 是一个 Python 软件包,它使所有水平的 Python 程序员都能创建 GUI。将 tkinter、Qt、WxPython 和 Remi(基于浏览器)GUI 框架转化为更简单的界面。通过使用初学者理解的 Python 核心数据类型(列表和字典),简化了窗口定义。通过将事件处理从基于回调的模式改为消息传递的模式,进一步简化了程序。

PySimpleGUI 代码比直接使用底层框架编写更简单、更短,因为 PySimpleGUI 为你实现了许多"boilerplate code"。此外,接口被简化为需要尽可能少的代码来获得所需的结果。根据所使用的程序和框架,一个 PySimpleGUI 程序可能需要 1/2 到 1/10 的代码来直接使用其中一个框架来创建一个相同的窗口。

虽然目标是封装/隐藏你在上面运行的 GUI 框架所使用的特定对象和代码,但如果需要,你可以直接访问框架的附属部件和窗口。如果一个设置或功能还没有使用 PySimpleGUI的API 暴露或访问,你就不会与框架隔阂。你可以在不直接修改 PySimpleGUI 包本身的情况下扩展功能。

你的代码不需要有一个面向对象的架构,这使得包可以被更多的人使用。虽然架构简单易懂,但它不一定限制你只能解决简单的问题。

示例一:

一个简单的 PySimpleGUI 程序剖析

PySimpleGUI 程序有 5 个部分

import PySimpleGUI as sg                        # Part 1 - The import

# Define the window's contents
layout = [  [sg.Text("What's your name?")],     # Part 2 - The Layout
            [sg.Input()],
            [sg.Button('Ok')] ]

# Create the window
window = sg.Window('Window Title', layout)      # Part 3 - Window Defintion
                                                
# Display and interact with the Window
event, values = window.read()                   # Part 4 - Event loop or Window.read call

# Do something with the information gathered
print('Hello', values[0], "! Thanks for trying PySimpleGUI")

# Finish up by removing from the screen
window.close()                                  # Part 5 - Close the Window

该代码生成了这个窗口:

示例二:

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()

浏览 4
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

编辑
举报