简体   繁体   English

如何从另一个线程更新GUI? 使用python

[英]How do I update the GUI from another thread? using python

What is the best way to update a gui from another thread in python. 从python中的另一个线程更新gui的最佳方法是什么。

I have main function (GUI) in thread1 and from this i'm referring another thread ( thread2 ), is it possible to update GUI while working in Thread2 without cancelling work at thread2 , if it is yes how can I do that? 我有主要功能(GUI) thread1 ,并从这个我指的另一个线程( thread2 ),是可以更新GUI在工作时, Thread2不会在取消工作thread2 ,如果是的话我该怎么办呢?

any suggested reading about thread handling. 任何有关线程处理的建议阅读。 ?

Of course you can use Threading to run several processes simultaneously. 当然,您可以使用Threading来同时运行多个进程。

You have to create a class like this : 您必须创建一个像这样的类:

from threading import Thread

class Work(Thread):

    def __init__(self):
        Thread.__init__(self)
        self.lock = threading.Lock()

    def run(self): # This function launch the thread
        (your code)

if you want run several thread at the same time : 如果要同时运行多个线程:

def foo():
    i = 0
    list = []
    while i < 10:
        list.append(Work())
        list[i].start() # Start call run() method of the class above.
        i += 1

Be careful if you want to use the same variable in several threads. 如果要在多个线程中使用同一变量,请小心。 You must lock this variable so that they do not all reach this variable at the same time. 您必须锁定此变量,以使它们不会同时全部到达此变量。 Like this : 像这样 :

lock = threading.Lock()
lock.acquire()
try:
    yourVariable += 1 # When you call lock.acquire() without arguments, block all variables until the lock is unlocked (lock.release()).
finally:
    lock.release()

From the main thread, you can call join() on the queue to wait until all pending tasks have been completed. 从主线程,您可以在队列上调用join()以等待所有未完成的任务完成。

This approach has the benefit that you are not creating and destroying threads, which is expensive. 这种方法的好处是您无需创建和销毁线程,这很昂贵。 The worker threads will run continuously, but will be asleep when no tasks are in the queue, using zero CPU time. 工作线程将连续运行,但是当队列中没有任何任务时,将使用零CPU时间进入睡眠状态。

I hope it will help you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM