首页 > 解决方案 > 如何在子线程中更新父类对象(self.progress)?

问题描述

我正在尝试运行进度状态栏来向用户发出正在执行任务的信号。我尝试了不同的策略但没有成功。

在这段代码中,问题是我无法从子线程更新进度条的值。我做错了什么。

import time
import threading
from tkinter import Tk, Button
from tkinter.ttk import Progressbar

class App():
    def __init__(self, root):
        self.button = Button(root)
        self.button.grid(row=1,column=0, padx=2,pady=2);
        self._resetbutton()
        self.progress = Progressbar(root, length=330, mode = 'determinate') 
        self.progress.grid(  row=2,column=0, columnspan=4,padx=2,pady=2);    

    def _resetbutton(self):
        self.running = False
        self.button.config(text="Start", command=self.startthread)
    def startthread(self):
        self.running = True
        newthread = threading.Thread(target=self.status_bar)
        newthread.start()
        self.button.config(text="Stop", command=self._resetbutton)

        for  x in range(12):
                time.sleep(.75)
                print(".");

    def status_bar( self ): 
        value = 0;
        print("started thread");

        while self.running:           
            value = ( value + 10 ) % 100;    
            #self.progress['value'] = value;   # <-- failure
            
            time.sleep(0.5); 
            print( value );

        print("done thread");

ventana_principal=Tk()
calculadora=App(ventana_principal)
ventana_principal.mainloop()

标签: pythonmultithreading

解决方案


在这里,您可以看到 startthread 函数中的更改以使此进度条正常工作。

def startthread(self):
    def status_bar( ): 
        value = 0;
        print("started thread");

        while self.running:           
            value = ( value + 10 ) % 100;    
            self.progress['value'] = value;   # <-- failure
            
            time.sleep(0.5); 
            print( value );

        print("done thread");


    def aux_func( ): 
        while self.running:           
                time.sleep(.75)
                print(".");
   

    self.running = True
    newthread = threading.Thread(target=status_bar)
    newthread.start()
    newthread2 = threading.Thread(target=aux_func)
    newthread2.start()
    self.button.config(text="Stop", command=self._resetbutton)

推荐阅读