Python3循环不工作
我是Python新手,目前仍在进行一些实验。我在家里有一个气象站,它链接到JSON Web API。我想通过Python读取屏幕上的温度 我遇到的问题是温度没有自我更新。当Python程序开始运行时,它将获得正确的温度。但是,如果温度发生变化,python脚本将停止运行。不会改变Python3循环不工作,python,json,tkinter,Python,Json,Tkinter,我是Python新手,目前仍在进行一些实验。我在家里有一个气象站,它链接到JSON Web API。我想通过Python读取屏幕上的温度 我遇到的问题是温度没有自我更新。当Python程序开始运行时,它将获得正确的温度。但是,如果温度发生变化,python脚本将停止运行。不会改变 import urllib.request import json from tkinter import * import tkinter as tk while True: key = "1234"
import urllib.request
import json
from tkinter import *
import tkinter as tk
while True:
key = "1234"
method = "getTemp"
data = json.load(urllib.request.urlopen('http://IP.COM/api/api.php?key=' + key + "&request=" + method))
temp = (data[u'temp'])
root = Tk()
root.title("Temperature board")
root.configure(background='#545454')
cv = tk.Canvas(width=1000, height=1000, background='#545454')
timeLabel = cv.create_text(200, 360, fill="white", text=temp, font=('Arial', 100))
cv.pack()
root.mainloop()
我试图创建一个循环来解决这个问题,但它似乎不起作用。root.mainloop()
阻塞,这意味着当它运行时,程序停止在那里。因此,您的循环实际上没有任何区别。您可以使用上面描述的解决方案中的一个运行函数来更新温度
从上面的答案中选择一个解决方案,您可以执行以下操作:
# setup
def update():
# update temperature
root.after(millis between updates, update)
root.after(millis between updates, update)
root.mainloop()
我建议不要调用方法
update
,因为tkinter小部件都已经有了一个名为update
的方法。如果函数的名称相同,但执行的操作不同,则可能会造成混淆,并导致错误。