我一直在用tkinter做一个初学的python桌面应用程序。 我通过API提取信息,并希望每10秒钟更新一次此信息。可悲的是,我无法通过线程和睡眠功能使其工作。 有什么建议吗?
from tkinter import *
import urllib.request
import json
import threading
from tkinter import ttk
import time
def main():
win = Tk()
win.tk_setPalette(background='black', foreground='white')
win.title('Crypto Desktop Ticker')
win.geometry('250x35')
#def getInfo():
url1 = urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/bitcoin/")
data1 = json.loads(url1.read())
priceusd = data1[0]['price_usd']
onehourchange = data1[0]['percent_change_1h']
output1 = ("BTC "+priceusd+"USD ("+onehourchange+"%)" )
url2 = urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/cardano/?convert=USD") #as url:
data2 = json.loads(url2.read())
priceusd = data2[0]['price_usd']
onehourchange = data2[0]['percent_change_1h']
output2 = ("ADA "+priceusd+"USD ("+onehourchange+"%)" )
T = Text(win, height=2, width=100)
T.pack()
T.insert(END, output1 + '\n' +
output2)
T.config(state=DISABLED)
win.mainloop()
time.sleep(10)
main()
#threading.Timer(10.0, main().start)
答案 0 :(得分:1)
创建一个获取数据并更新GUI的函数。使用此方法使用after
来安排自己每10秒运行一次。
def refresh():
# get the information
info = <your code to get the information>
# update the display
T.configure(state="normal")
T.delete("1.0", "end")
T.insert("end", info)
T.configure(state="disabled")
# call again in 10 seconds
win.after(10000, refresh)