如何在Python中每3小时更新一次URL

时间:2018-11-06 20:30:09

标签: python tkinter

我是一个尝试学习编程的老家伙。我曾尝试寻找该问题的答案,但大多数答复都超出了我的理解范围。因此,在这里,我编写了代码来从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()

在此先感谢您的协助!这对我来说是全新的(几个星期),因此请您详细解释。

2 个答案:

答案 0 :(得分:4)

您想在此处使用after函数,该函数将在TKinter的主循环中运行代码。您在这里谈到了一些重要的事情;该过程一次只能执行一件事,因此您需要tk中的mainloop来跟踪何时运行代码,以便它可以在此期间完成其余工作。

def task():
    print("hello")
    # do your extractions
    main_window.after(60000, task)  # reschedule event in 60 seconds

main_window.after(60000, task)
main_window.mainloop()

这将在主循环开始之前安排一个任务,该任务将在60000毫秒(或60秒)内运行。 task可以是您定义的任何函数。

运行task时,它还会安排它自己完成时的另一次执行。然后,您可以在task函数中完成工作。

答案 1 :(得分:0)

我能够找到解决此问题的方法。

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)

因为已经调用了URL,所以我必须在函数中添加“ global”,因此它将知道使用全局变量而不是函数的局部变量。