我是一个试图学习编程的老人.我试过寻找这个问题的答案,但大多数回复都是我的头脑.所以这里,我编写了代码来从Web获取数据,将其转换为json,并以所需的格式打印结果.我现在正在使用Tkinter来显示这些数据.我已成功显示数据并更新标签,但我无法获取更新的URL(为标签提供输入).那么如何在预定的时间间隔内(每3小时一次)更新或运行request.get而不使用可以阻止其余程序的循环?
这是我到目前为止所做的(要运行此程序,您需要从openweather.com输入您的api)....
import requests
import time
from tkinter import *
# Input Values
api = 'Enter API Key from Openweather.com'
lat = '33.608'
lon = '-111.863'
unit = 'imperial' # unit must be 'imperial' or 'metric'
fcast_time = [0, 4, 8, 12, 16, 20, 24, 28] # each element is a 3 hour period (i.e. 4 would be 12 hours out), max is 40
main_window = Tk()
url2 = 'http://api.openweathermap.org/data/2.5/forecast?'+'lat='+str(lat)+'&lon='+str(lon)+'&APPID='+str(api)+'&units='+str(unit)
def fconvertTime(tperiod):
period = fcast_data['list'][fcast_time[tperiod]]['dt']
ftime = time.strftime("%a %p", time.localtime(period))
return(ftime)
r_forecast = requests.get(url2)
fcast_data = (r_forecast.json())
def forecast_layout(frame_name, tperiod):
label_fcast_day = Label(frame_name, text=fconvertTime(tperiod), justify=CENTER, font=("Ariel", 8), bg="black",
fg="white", width=13)
label_test_update = Label(frame_name, text=time.strftime('%H:%M:%S'), justify=CENTER, font=("Ariel", 8), bg="black",
fg="white", width=13)
label_fcast_day.grid(row=0, column=0)
label_test_update.grid(row=3, column=0)
# Configure Main Window
main_window.title("Weather")
main_window.geometry("705x500")
main_window.resizable(True, True)
main_window.configure(bg="black")
# Define sub-frames
forecast_frame = Frame(main_window, bg="blue")
forecast_frame.grid(row=0, column=0, columnspan=3)
# Build forecast_frame
frame_fcast1 = Frame(forecast_frame)
forecast_layout(frame_fcast1, 0)
frame_fcast1.grid(row=0, column=0, pady=2, padx=2, sticky=W)
frame_fcast2 = Frame(forecast_frame)
forecast_layout(frame_fcast2, 1)
frame_fcast2.grid(row=0, column=1, pady=2, padx=2, sticky=W)
main_window.mainloop()
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助!这对我来说都是非常新的(几周),所以我们将非常感谢您的详细解释.
我能够找到解决这个问题的方法。
update_frequency = 10800000 #value is in millisecends
def url2_renew():
global r_forecast
global fcast_data
r_forecast = requests.get(url2)
fcast_data = (r_forecast.json())
main_window.after(update_frequency, url2_renew)
Run Code Online (Sandbox Code Playgroud)
因为 URL 已经被调用,所以我必须在函数中添加“全局”,这样它就会知道使用全局变量而不是函数的本地变量。
| 归档时间: |
|
| 查看次数: |
140 次 |
| 最近记录: |