Pysimple Gui多线程

该代码示例展示了如何在PySimpleGUI中使用多线程进行通信。通过窗口的`write_event_value`方法,线程能以非阻塞的方式发送事件和值到主线程。当点击“Start”按钮时,会启动新线程,主线程则通过监听事件来接收并处理来自线程的数据。同时,文章提到了旧的多线程机制与新机制的差异,强调了新机制对性能的积极影响。
摘要由CSDN通过智能技术生成

Pysimple Gui多线程

import threading
import time
import PySimpleGUI as sg

"""
    Threaded Demo - Uses Window.write_event_value communications

    Requires PySimpleGUI.py version 4.25.0 and later

    This is a really important demo  to understand if you're going to be using multithreading in PySimpleGUI.

    Older mechanisms for multi-threading in PySimpleGUI relied on polling of a queue. The management of a communications
    queue is now performed internally to PySimpleGUI.

    The importance of using the new window.write_event_value call cannot be emphasized enough.  It will hav a HUGE impact, in
    a positive way, on your code to move to this mechanism as your code will simply "pend" waiting for an event rather than polling.

    Copyright 2020 PySimpleGUI.org
"""

THREAD_EVENT = '-THREAD-'

cp = sg.cprint

def the_thread(window):
    """
    The thread that communicates with the application through the window's events.

    Once a second wakes and sends a new event and associated value to the window
    """
    i = 0
    while True:
        time.sleep(3)
        window.write_event_value('-THREAD-', (threading.current_thread().name, i))      # Data sent is a tuple of thread name and counter
        cp('This is cheating from the thread', c='white on green')
        i += 1

def main():
    """
    The demo will display in the multiline info about the event and values dictionary as it is being
    returned from window.read()
    Every time "Start" is clicked a new thread is started
    Try clicking "Dummy" to see that the window is active while the thread stuff is happening in the background
    """

    layout = [  [sg.Text('Output Area - cprint\'s route to here', font='Any 15')],
                [sg.Multiline(size=(65,20), key='-ML-', autoscroll=True, reroute_stdout=True, write_only=True, reroute_cprint=True)],
                [sg.T('Input so you can see data in your dictionary')],
                [sg.Input(key='-IN-', size=(30,1))],
                [sg.B('Start A Thread'), sg.B('Dummy'), sg.Button('Exit')]  ]

    window = sg.Window('Window Title', layout, finalize=True)

    while True:             # Event Loop
        event, values = window.read()
        cp(event, values)
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
        if event.startswith('Start'):
            threading.Thread(target=the_thread, args=(window,), daemon=True).start()
        if event == THREAD_EVENT:
            cp(f'Data from the thread ', colors='white on purple', end='')
            cp(f'{values[THREAD_EVENT]}', colors='white on red')
    window.close()

if __name__ == '__main__':
    main()

lambda示例

    def myfun(str):
        return str
    a = lambda :myfun('123')
    print(a())

perform_long_operation

import PySimpleGUI as sg
import time

def my_function():
    time.sleep(30)
    return '30秒'

def my_function_with_parms(duration):
    time.sleep(duration)
    return 'My Return Value'

layout = [  [sg.Text('Call a lengthy function')],
            [sg.Button('Start'), sg.Button('Start 2'), sg.Button('Exit')]  ]

window = sg.Window('Long Operation Example', layout)

while True:
    event, values = window.read()
    print(event, values)
    if event == sg.WIN_CLOSED or event == 'Exit':
        break
    if event == 'Start':
        window.perform_long_operation(my_function, '-FUNCTION COMPLETED-')
    elif event == 'Start 2':
        window.perform_long_operation(lambda: my_function_with_parms(10), '-FUNCTION COMPLETED-')
    elif event == '-FUNCTION COMPLETED-':
        sg.popup('Your function completed!')
window.close()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值