【发布时间】:2021-10-06 19:03:51
【问题描述】:
我仍在制作我的天气应用程序,我需要一个更改城市或国家/地区的功能,问题是我必须重新启动程序才能显示更改,但是当我重新启动时 - 加载默认城市而不是新的,我尝试了很多方法来解决这个问题,但都没有奏效,提前谢谢!
# !/usr/bin/python3
#Please don't use my API-KEY for bad purposes, I have only included it to help run the code
import requests, json
from tkinter import *
import os
CITY = "Glasgow"
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
URL = "https://api.openweathermap.org/data/2.5/weather?q=+" + CITY + "&units=metric&APPID=confedential"
response = requests.get(URL)
def func() :
def change():
y = Toplevel()
y.geometry("200x100")
en = Entry(y, width=10)
en.place(x=25, y=25)
en.focus()
def getr(e):
def restart():
x.destroy()
func()
CITY = en.get()
restart()
en.bind("<Return>", getr)
if response.status_code == 200:
data = response.json()
main = data['main']
temperature = main['temp']
humidity = main['humidity']
pressure = main['pressure']
report = data['weather']
print(f"{CITY:-^30}")
print(f"Temperature: {temperature}")
print(f"Humidity: {humidity}")
print(f"Pressure: {pressure}")
print(f"Weather Report: {report[0]['description']}")
rep = report[0]['main'].lower()
if "clear" in rep:
image = 'images/sunny.png'
if "cloud" in rep:
image = 'images/cloud.png'
if "rain" in rep:
image = 'images/rain.png'
if "thunder" in rep:
image = 'images/thunder.png'
if "mist" in rep:
image = 'images/mist.png'
if "snow" in rep:
image = 'images/snow.png'
x = Tk()
# Creating Menubar
menubar = Menu(x)
menubar.config(bg="#484848", fg="white", font=("Stencil Std", 10))
# Adding Help Menu
help_ = Menu(menubar, tearoff=0, bg="#484848", fg="white", font=("Stencil Std", 10))
menubar.add_cascade(label='Countries', menu=help_)
help_.add_command(label='Change Current Country', command=change)
help_.add_command(label='Show Current Country', command=None)
help_.add_separator()
help_.add_command(label='Change Timezone', command=None)
help_.add_command(label='Show Current Timezone', command=None)
help_.add_separator()
help_.add_command(label="Exit", command=x.destroy)
# display Menu
x.config(menu=menubar)
x.resizable(False, False)
gif = PhotoImage(file=image)
cvwid = gif.width()
cvhei = gif.height()
canvas = Canvas(x, width=cvwid, height=cvhei, bg='lightblue')
canvas.pack(fill=BOTH)
img = canvas.create_image(0, 0, image=gif, anchor=NW)
temp = canvas.create_text(cvwid / 2, 350, fill="White", font="Helvetica 30", text=str(int(temperature)) + "°C")
reportr = canvas.create_text(cvwid / 2, 400, fill="White", font="Helvetica 20", text=report[0]["main"])
x.title(f"{CITY:-^30}")
x.mainloop()
func()
【问题讨论】:
-
为什么有这么多嵌套函数?有全局变量是有原因的。您是否也尝试过将
URL = ...和response = ...放在可以调用以获取更新信息的函数中? -
如果有人不诚实地使用您的密钥,那么友好地询问他们并不是一个成功的策略。您需要尽快删除这些凭据,并且您可能需要联系版主将其从问题历史记录中删除。
标签: python-3.x tkinter openweathermap