Tkinter pyowm无法更新

时间:2019-01-07 19:04:47

标签: python tkinter label auto-update openweathermap

我有几个小部件,或更正确的说是Label,当在self.after()中调用以__init__. 结尾的方法时,它们可以完美地更新 这里的标签不是这种情况,它通过pyowm从OWM(OpenWeatherMap)获取天气信息,并应在after()函数中定义的每个特定时间进行更新。

尽管我是Python的新手,但我已经尝试了几乎所有知识。我已经在Google搜索了好几天,但没有找到有效的解决方案,或者没有找到可以解决的方案。 我试图将after函数放在每种方法中,甚至是__init__

经过精简的main()用于调试和天气类如下:

import tkinter as tk
from Weather import Meteo


def displayMeteo(win):
    # Place Meteo portlet
    meteoHandler = Meteo(win, bg='black', fg='white')
     meteoHandler.pack(side='top', anchor='ne')


def main():
    # Set the screen definition, root window initialization
    root = tk.Tk()
    root.configure(background='black')
    width, height = root.winfo_screenwidth(),
    root.winfo_screenheight()
    root.geometry("%dx%d+0+0" % (width, height))
    label = tk.Label(root, text="Monitor Dashboard", bg='black',
                     fg='red')
    label.pack(side='bottom', fill='x', anchor='se')

    # Display portlet
    displayMeteo(root)

    # Loop the GUI manager
    root.mainloop(0)


###############################
#     MAIN SCRIPT BODY PART   #
###############################
if __name__ == "__main__":
    main()

和班级

import pyowm
import tkinter as tk
from PIL import Image, ImageTk


class Meteo(tk.Label):
    def __init__(self, parent=None, **params):
        tk.Label.__init__(self, parent)
        self.API = pyowm.OWM('API KEY', config_module=None,
                         language='it', subscription_type=None)
        self.location = self.API.weather_at_place('Rome,IT')
        self.weatherdata = self.location.get_weather()
        self.weather = str(self.weatherdata.get_detailed_status())
        self.dictionary = {'poche nuvole': 'Parzialmente Nuvoloso',
        'cielo sereno': 'Sereno', 'nubi sparse': 'Nuvoloso',
        'temporale con pioggia': 'Temporale', 'pioggia leggera':
        'Pioggerella'}

        self.Display()

def Temperatur(self):
    self.Temp = tk.StringVar()

    self.tempvalue = self.weatherdata.get_temperature('celsius')
    self.temperature = str(self.tempvalue.get('temp'))

    self.Temp.set(self.temperature)
    self.after(3000, self.Temperatur)

def WeatherInfo(self):
    self.Weather = tk.StringVar()

    self.weather = str(self.weatherdata.get_detailed_status())
    if self.weather in self.dictionary:
        self.weather = self.dictionary[self.weather]

    self.weatherstring = self.weather.title()

    self.Weather.set(self.weatherstring)
    self.after(3000, self.WeatherInfo)

def Display(self):
    self.Temperatur()
    self.WeatherInfo()
    self.configure(text=self.Weather.get() + ",   " + self.Temp.get() + "°", bg='black',
                   fg='#FFFF96', font=("arial, 35"))
    self.after(3000, self.Display)

现在,应该发生的是小部件每3秒更新一次(只是为了调试),尽管我知道即使更新有效,它也不会每3秒更改一次,因为您知道...天气不会每次更改3秒。

1 个答案:

答案 0 :(得分:1)

如建议Idlehands所做的那样,问题不在标签或更新中。 如果以这种方式编写,则该代码只会调用一次.get_weather,从而造成停滞的变量。我添加了一种更新pyowm解析的方法,现在一切正常!