在Python和Tkinter完成线程之前,访问队列



我正在使用tkinter为基于代理的模型构建GUI。该模型以"年度"时间步骤运行。我正在尝试使用螺纹来获取Model.py在每个时间步(即每个"年"(与GUI通信。

当前模型。

def run_model(self, step_count, thread_queue = None): 
    for i in range(step_count):
       self.thread_queue.put(self.time)
       self.step()

在上述函数中,step_count简单地告诉模型它应该运行多少年,而self.step函数运行了一个"年"的模型。

在gui.py中,我目前执行以下操作:

def run_model(self):
    data = [
        {'b_min_t': self.b_min_t.get()},
        {'b_max_t': self.b_max_t.get()},
        {'sc_min_t': self.sc_min_t.get()},
        {'sc_max_t': self.sc_max_t.get()},
    ]
    self.mylabel.config(text='Running Model')
    # set time to run model
    model_run_years = 5
    # run model, collect outputs and save dataframe
    self.run_model_thread = threading.Thread(target=self.model.run_model(model_run_years, self.thread_queue), daemon=True)
    self.run_model_thread.start()
    self.after(1000, self.listen_for_result)
def listen_for_result(self):
    '''
    Check if there is something in the queue
    '''
    try:
        self.res = self.model.thread_queue.get()
        self.mylabel.config(text=self.res)
    except queue.Empty:
        self.after(1000, self.listen_for_result)

此当前实现显然无法使用,因为self.mylabel.config直到模型在model_run_years中指定的时间上运行后才更新。谁能向我指出实现自己追求的最佳方法的方向?从本质上讲,我希望GUI在每个self.step()之后更新self.mylabel.config-我在最终想在GUI中显示的后台运行图形,这需要每个"年"。

谢谢!

直到最后。只是从线程中从GUI内部运行步骤函数的情况。

最新更新