如何从另一个线程类更新进度条?

时间:2019-01-20 13:59:55

标签: python multithreading tkinter progress-bar

我目前正在使用Python开发一个简单的神经网络,但是在Tkinter和多线程方面遇到了麻烦。

我有2个类,一个类用于接口,另一个类用于计算。

我的界面类中有一个进度条和一个按钮,用于在另一个线程中调用计算工作类中的函数。我想要这个被调用的函数来更新我的progressBar的值。 (例如,每测试1000个项目)

这就是我的代码(简体):

接口:

class UInterface:

    def __init__(self):
       self.window = Tk()
       self.nh = NetworkHelper()
       self.progress_value = 0
       self.test_result = Label(window, text="").grid(row=0, column =1)
       Button(self.window, text="Test", command=partial(self.test)).grid(row=1, column =1)
       self.progress = ttk.Progressbar(orient="horizontal", maximum=117, mode="determinate")
       self.progress.grid(row=3, column =1)
       self.window.mainloop()

    def test(self):
       pool = ThreadPool(processes=1)

       async_result = pool.apply_async(self.nh.test)

       while results == None
          self.progress["value"] = self.progress_value 
          self.window.update()

       results = async_result.get()

       self.test_result.config(text=str(results) + "% of good answers")

这是我在NetworkHelper类中的测试函数,在进行艰苦的工作:

def test(self):
    total_answer = 0
    good_answer = 0
    # preparing data and testing
    for i in range(self.data_test_length):
        ## Some testing 
        total_answer += 1
        ## TODO Update progress_value in class Interface

    return good_answer/total_answer

我尝试了一些方法,例如从NH.test调用Interface中的函数,但是由于它不是同一线程,所以我什么也无法更新。我还尝试了Queues,但无法使其正常工作。

0 个答案:

没有答案
相关问题