python - 从 API 获取数据时 tkinter 窗口无响应
问题描述
我有一个 tkinter 程序,它从 API 获取一些数据。当互联网连接速度很慢时,可能需要很长时间。tkinter 窗口变得无响应。要阻止它,我必须强制关闭程序。我该如何避免这种情况?
我有一个被称为从 API 检索数据的函数。我希望能够在保持程序和 tkinter 窗口运行的同时停止该功能。
上传图片后,我将其上传到 API(这显然需要一些时间),在收到响应后,将检索到的相关信息粘贴到 txt 文件中并打开它。
解决方案
使用线程进行调用和递归事件检查,直到调用完成。
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()
推荐阅读
- typescript - 当即时需要第二个泛型参数时,如何仅使用一个泛型参数调用泛型函数?
- javascript - 如何使图表背景透明
- python - 实时交通摄像头抓取
- jsf - 覆盖 PrimeFaces 的 MediaRenderer
- c++ - 反向功能超出了我的 cpp 程序的范围
- java - 即使覆盖 JPanel 的 paintComponent() 方法,Java 图形也不会在 Mac 上显示
- amazon-web-services - 如何为许多 s3 对象创建一个冰川档案?
- linux - 通过 shell 脚本参数化 Curl 请求
- kubernetes - 如何阻止我的(k8s)入口中的路径?
- asp.net-core - 如何自动启动/预热 IIS 中托管的 .net 核心 Web 应用程序