![](/img/trans.png)
[英]What is the best way to repeatedly execute a function in Python?
[英]What is the best way to repeatedly execute a function every few seconds, without intterupting other functions, for a Python gui?
我想重復運行一個每隔60秒從API檢索數據的函數。 但是,我意識到我不能讓它睡覺,或者使用while循環,而不會中斷其他功能。
我的問題是,如何重復從API中檢索數據/重新運行首先獲取數據的代碼,而不中斷其他功能?
在一個完整的腳本下方,從Open Notify檢索ISS位置經度和緯度並在線程上打印。
我已經設定了1秒鍾。 您可以啟動和停止線程。 現在嘗試添加您的功能。
請注意,您必須導入此模塊
導入請求
導入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.