创建wind后在后台运行代码

2024-05-04 02:56:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为现有的Python代码创建一个基本的GUI,但是大多数允许创建用户界面的框架都需要某种窗口循环。我想创建一个带有按钮的窗口,在运行代码时“监听”按钮的按下。你知道吗

使用伪代码:

CreateWindowWithButton(window, button1, button1.text = "False")
arg = False
while(True):
    do_something(arg)
    if window.button1.isPressed():
        arg = not arg
        window.button1.text = str(arg)
    if keypressed("Escape"):
        break
DestroyWindow(window)

Tags: 代码text框架falsetrueifarggui
1条回答
网友
1楼 · 发布于 2024-05-04 02:56:51

既然您还没有指定GUI框架,我建议您尝试PySimpleGUI,一个tkinter包装器。你知道吗

这段代码创建了一个带有按钮的窗口,然后在while循环中读取按钮,就像您的示例伪代码一样。你知道吗

import PySimpleGUI as sg

layout = [[sg.Text('Click the button to trigger main loop')],
          [sg.RButton('My Button')]]

window = sg.Window('My new window').Layout(layout)

while True:                                         # Event Loop
    # do_something()                                # Do whatever you want
    button, value = window.ReadNonBlocking()        # Reads without blocking the program (like polling)
    if value is None:                               # If X button was clicked
        break
    elif button == 'My Button':                       # If got the button click we want
        print('Received the button press')
        break

代码生成此窗口:

enter image description here

相关问题 更多 >