首页 > 解决方案 > 在 Jupyter 上运行 PySimpleGUI

问题描述

PySimpleGUI 如何在 Web 上使用(尤其是 Jupyter)?应该改用 PySimpleGUIWeb 吗?我知道它可以在 repli 上运行,但我想要的是其他地方。

标签: pysimplegui

解决方案


您可以在 Jupyter 中同时使用 PySimpleGUIWeb 和 PySimpleGUI,但您的决定取决于您的用例。

如果您尝试在运行代码的计算机上运行 GUI,则可以使用 PySimpleGUI。您需要在具有桌面环境的操作系统上运行代码。

如果您希望从任何其他计算机访问 GUI,您将需要使用 PySimpleGUIWeb。

示例 1: 在 Jupyter 中使用 PySimpleGUI

import PySimpleGUI as sg

sg.theme('DarkAmber')   # Add a touch of color
# All the stuff inside your window.
layout = [  [sg.Text('Some text on Row 1')],
            [sg.Text('Enter something on Row 2'), sg.InputText()],
            [sg.Button('Ok'), sg.Button('Cancel')] ]

# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
        break
    print('You entered ', values[0])

window.close()

示例代码来自:https ://pysimplegui.readthedocs.io/en/latest/#jump-start

示例 2: 在 Jupyter 中使用 PySimpleGUIWeb

import PySimpleGUIWeb as sg

layout = [  [sg.Text('My Window')],
            [sg.Input(key='-IN-'), sg.Text(size=(12,1), key='-OUT-')],
            [sg.Button('Go'), sg.Button('Exit')]  ]

window = sg.Window('Window Title', layout, web_port=2222, web_start_browser=False)

while True:             # Event Loop
    event, values = window.read()
    print(event, values)
    if event in (None, 'Exit'):
        break
    if event == 'Go':
        window['-OUT-'].Update(values['-IN-'])
window.close()

示例代码来自:https ://github.com/PySimpleGUI/PySimpleGUI/issues/2462

当我刚刚测试 PySimpleGuiWeb 代码时,我使用 Python 3.9 弹出导入错误,所以我降级到 Python 3.8.12 并且效果很好。

运行 PySimpleGuiWeb 版本时,导航到http://0.0.0.0:2222/以查看窗口。

您显然需要在您的环境中安装 PySimpleGUIWeb 和 PySimpleGUI 才能运行代码。

此外,您可能需要弄乱路由器上的防火墙规则才能从其他计算机访问 PySimpleGUIWeb 实例。


推荐阅读