【问题标题】:How do I restart my program without restarting the variable declarations如何在不重新启动变量声明的情况下重新启动程序
【发布时间】: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


【解决方案1】:

问题是您只分配了一次response = requests.get(URL)。无论您多久更换一次城市,使用参数"Glasgow" 建立的响应将始终保持不变。

在不重构整个代码库的情况下,最快的修复方法是将 CITYresponse 设为全局,以便您可以在函数内修改它们。例如:

CITY = "Glasgow"
URL = "https://api.openweathermap.org/data/2.5/weather?q=+{}&units=metric&APPID=confidential"

def get_response(city=CITY):
    return requests.get(URL.format(city))

response = get_response()

然后您可以像这样在 getr(e) 函数中全局化您的变量。

def getr(e):                 
    global CITY, response
    CITY = en.get()
    response = get_response(CITY)
    restart()

这是您当前遇到的问题的解决方案。但是我建议,回到你的代码库。有了一个好的重构,你就不需要这个:你可以考虑分离逻辑和用户界面,让你的函数接受参数并将它们彼此分离,研究如何在运行的 Tk() 主循环中更新/更改显示值而不是破坏和回忆它。将您的代码发布在stackexchange for codereview 上也许会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2018-12-28
    • 2020-12-23
    • 2019-12-15
    • 1970-01-01
    • 2016-04-16
    相关资源
    最近更新 更多