[英]What is the best way to repeatedly execute a function every few seconds, without intterupting other functions, for a Python gui?
I want to repeatedly run a function that retrieves data from an API every 60 seconds. 我想重复运行一个每隔60秒从API检索数据的函数。 However, I've realized that I can't put it to sleep, or use a while loop, without interrupting the other functions.
但是,我意识到我不能让它睡觉,或者使用while循环,而不会中断其他功能。
My question is, how do I repeatedly retrieve the data from the API/rerun the code that gets the data in the first place, without interrupting the other functions? 我的问题是,如何重复从API中检索数据/重新运行首先获取数据的代码,而不中断其他功能?
below a complete script that retrieve ISS position longitude and latitude from Open Notify and print it on a thread. 在一个完整的脚本下方,从Open Notify检索ISS位置经度和纬度并在线程上打印。
I' ve set a 1 second time. 我已经设定了1秒钟。 You can start and stop the thread.
您可以启动和停止线程。 Try now you to add your funcions.
现在尝试添加您的功能。
Notice that you have to import this modules 请注意,您必须导入此模块
import requests
导入请求
import json
导入json
import tkinter as tk
import threading
import queue
import datetime
import time
import requests
import json
class MyThread(threading.Thread):
def __init__(self, queue,):
threading.Thread.__init__(self)
self.queue = queue
self.check = True
def stop(self):
self.check = False
def run(self):
while self.check:
response = requests.get("http://api.open-notify.org/iss-now.json")
data = response.json()
time.sleep(1)
self.queue.put(data)
class App(tk.Frame):
def __init__(self,):
super().__init__()
self.master.title("Hello World")
self.master.protocol("WM_DELETE_WINDOW",self.on_close)
self.queue = queue.Queue()
self.my_thread = None
self.init_ui()
def init_ui(self):
self.f = tk.Frame()
w = tk.Frame()
tk.Button(w, text="Start", command=self.launch_thread).pack()
tk.Button(w, text="Stop", command=self.stop_thread).pack()
tk.Button(w, text="Close", command=self.on_close).pack()
w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=0)
self.f.pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
def launch_thread(self):
if (threading.active_count()!=0):
self.my_thread = MyThread(self.queue)
self.my_thread.start()
self.periodiccall()
def stop_thread(self):
if self.my_thread is not None:
if(threading.active_count()!=1):
self.my_thread.stop()
def periodiccall(self):
self.checkqueue()
if self.my_thread.is_alive():
self.after(1, self.periodiccall)
else:
pass
def checkqueue(self):
while self.queue.qsize():
try:
ret = self.queue.get(0)
print("The ISS is currently over: {0} ".format(ret['iss_position']))
except queue.Empty:
pass
def on_close(self):
if self.my_thread is not None:
if(threading.active_count()!=1):
self.my_thread.stop()
self.master.destroy()
if __name__ == '__main__':
app = App()
app.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.