创建窗口后在后台运行代码

时间:2018-10-10 07:51:55

标签: python user-interface

我想为现有的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)

1 个答案:

答案 0 :(得分:0)

由于您尚未指定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