首页 > 解决方案 > 从 API 获取数据时 tkinter 窗口无响应

问题描述

我有一个 tkinter 程序,它从 API 获取一些数据。当互联网连接速度很慢时,可能需要很长时间。tkinter 窗口变得无响应。要阻止它,我必须强制关闭程序。我该如何避免这种情况?

我有一个被称为从 API 检索数据的函数。我希望能够在保持程序和 tkinter 窗口运行的同时停止该功能。

在此处输入图像描述

上传图片后,我将其上传到 API(这显然需要一些时间),在收到响应后,将检索到的相关信息粘贴到 txt 文件中并打开它。

标签: pythontkinter

解决方案


使用线程进行调用和递归事件检查,直到调用完成。

from threading import Thread
from time import sleep
import tkinter as tk

class App(tk.Tk):

    def api_call(self, time):
        sleep(time)
        print('API call done')
        self.api_result = 10

    def on_button_click(self):
        self.button.config(state=tk.DISABLED)
        self.api_thread = Thread(target=self.api_call, args=(3,))
        self.api_thread.start()
        self.button_update()

    def __init__(self):
        tk.Tk.__init__(self)

        self.api_thread = None
        self.api_result = None

        self.button = tk.Button(self, text='Send', command=self.on_button_click)
        self.button.place(relx=0.5, rely=0.5, anchor=tk.CENTER)

    def button_update(self):
        if self.api_result is not None:
            if self.api_thread.is_alive():
                self.api_thread.join(timeout=2)
            self.button.config(state=tk.NORMAL)
            self.api_thread = None
            self.api_result = None
        else:
            self.button.after(500, self.button_update)


if __name__ == '__main__':
    aplication = App()
    aplication.mainloop()

推荐阅读