gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:04:39 26 4
gpt4 key购买 nike

我是一个想学习编程的老人。我试过寻找这个问题的答案,但大多数回复都超出了我的理解范围。因此,我已经编写了代码以从 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()

提前感谢您的帮助!这对我来说都是全新的(几周),所以请提供详细的解释。

最佳答案

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

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 函数中完成您的工作。

关于python - 如何在 Python 中每 3 小时更新一次 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53179545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com