python:如何在gui中显示最新线程

rbl8hiat  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(477)

我正在使用gui显示一个倒计时计时器,当用户单击开始倒计时时,该计时器将被激活。使用另一个线程来计算倒计时计时器,但是我只需要在显示器上写入最新的线程,而不是在显示器上写入多个线程。

  • 按钮可以多次单击(或用于重置倒计时),只需显示最新的线程数据。
import time
import logging
import threading
import PySimpleGUI as sg
cp = sg.cprint
def main():
    sg.theme('DarkAmber')
    col1 = [[sg.Button('start countdown', button_color='white on green', size=(18, 5), font=('Arial', 30, 'bold'))],
            [sg.Button('Buzzer Stop', button_color='red', font=('Arial', 30, 'bold'), size=(18, 5))
             ]]
    col2 = [[sg.Multiline(size=(100, 2), key='-AB-', font=('Arial', 50, 'bold'), reroute_stdout=True, write_only=True,
                          reroute_cprint=False)],
            [sg.Multiline(size=(100, 6), key='-ML-', autoscroll=True, reroute_stdout=True, write_only=True,
                          reroute_cprint=True)]
            ]
    layout_test = [[sg.Column(col1, element_justification='c'), sg.Column(col2, element_justification='c')]]

    window = sg.Window('Counter', layout_test, size=(800, 480))
    while True:
        event, values = window.read()
        cp(event, values)
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
        if event.startswith('start countdown'):
            t = 900
            t1 = threading.Thread(target=countdown, args=(t, window), daemon=True).start()
        if event.startswith('Buzzer Stop'):
            threading.Thread(target=Samplingthread, args=(window,), daemon=True).start()
            Buzzerflag = 60
    window.close()
def countdown(t, window):
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        window['-AB-'].print(timer)
        time.sleep(1)
        t -= 1
if __name__ == '__main__':
    main()
pinkon5k

pinkon5k1#

不更新线程中的gui。

from time import sleep
import threading
import PySimpleGUI as sg

def count_down(window):
    count = 100
    while count and countdown:
        window.write_event_value("COUNT", count)
        count -= 1
        sleep(1)

def count_up(window):
    count = 0
    while not countdown:
        window.write_event_value("COUNT", count)    # CANNOT update GUI in thread
        count += 1
        sleep(1)

sg.theme('DarkBlue3')

layout = [
    [sg.Button('COUNTDOWN'), sg.Button('TIMER')],
    [sg.Text('', size=(20, 1), key='LABEL')],
]

window = sg.Window('TITLE', layout, finalize=True)
label = window['LABEL']
countdown = False

while True:

    event, values = window.read()

    if event == sg.WINDOW_CLOSED:
        break
    elif event == 'COUNTDOWN':
        countdown = True
        threading.Thread(target=count_down, args=(window,), daemon=True).start()
    elif event == 'TIMER':
        countdown = False
        threading.Thread(target=count_up, args=(window,), daemon=True).start()
    elif event == 'COUNT':
        label.update(value=values[event])

countdown = not countdown
sleep(1)
window.close()

相关问题