简体   繁体   English

如何从类调用启动函数

[英]How to call startup function from class

I am learning to use classes and I would like to call my GetWeather class from another MainApplication class. 我正在学习使用类,我想从另一个MainApplication类调用我的GetWeather类。

Upon calling GetWeather.coords I want to to start with a function that receives the required data. 在调用GetWeather.coords我想从一个接收所需数据的函数开始。

Below is my code so far: 以下是我目前的代码:

API_ID = '///foo///'

class GetWeather:
    def __init__(self, city, country):
        url_city = 'http://api.openweathermap.org/data/2.5/weather?q={},{}&appid={}'.format(city, country, API_ID)
        weatherdata = requests.get(url_city).json()
    def coords(self):
        print(weatherdata)

class MainApplication:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)


        self.button1 = tk.Button(self.frame, text = 'Coords', width = 25, command = GetWeather.coords('town','country'))
        self.button1.pack()


        self.frame.pack()



def main():
    root = tk.Tk()
    app = MainApplication(root)
    root.mainloop()

if __name__ == "__main__":
    main()

To create an instance of a class, call it like as if it were a function that just so happened to return a GetWeather object. 要创建一个类的实例,请将其称为就像它是一个返回GetWeather对象的函数一样。

Also, the argument to tkinter.Button 's command should be something it can call again, meaning you should pass it a function that hasn't been called yet. 此外, tkinter.Button command的参数应该是它可以再次调用的东西,这意味着你应该传递一个尚未被调用的函数。 Note the missing parentheses after GetWeather('town','country').print_coords . 请注意GetWeather('town','country').print_coords之后缺少的括号GetWeather('town','country').print_coords

Here's your fixed code: 这是你的固定代码:

import tkinter as tk

import requests

API_ID = '///foo///'

class GetWeather:

    def __init__(self, city, country):
        url_city = 'http://api.openweathermap.org/data/2.5/weather?q={},{}&appid={}'.format(city, country, API_ID)
        # note: save the weather data in 'self'
        self.weatherdata = requests.get(url_city).json()

    def print_coords(self):
        # get the stored weather data
        print(self.weatherdata)


class MainApplication:

    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)

        self.button1 = tk.Button(
            self.frame, text='Coords', width=25, 
            command=GetWeather('town', 'country').coords,
        )
        self.button1.pack()

        self.frame.pack()


def main():
    root = tk.Tk()
    app = MainApplication(root)
    root.mainloop()

if __name__ == "__main__":
    main()

There's nothing preventing you from doing that, but you do have make sure the function has the information it need available. 没有什么可以阻止你这样做,但你确实已经确保该功能具有所需的信息。 Since coords() is a method of class GetWeather , this can be done by simply saving the values passed to it when an instance of the class is created, then using it. 由于coords()GetWeather类的方法,因此可以通过在创建类的实例时保存传递给它的值,然后使用它来完成。

Below is an example code showing how to do that, and it will call the function to retrieve the data each time the Button is clicked (unlike @GeeTransit's answer which only retrieves the data once when button1 is initially created). 下面是一个示例代码,显示了如何执行此操作,并且每次单击Button时都会调用该函数来检索数据(与@ GeeTransit的答案不同,后者仅在最初创建button1时检索一次数据)。

API_ID = '///foo///'

class GetWeather:
    def __init__(self, city, country):
        self.city = city
        self.country = country

    def coords(self):
        url_city = ('http://api.openweathermap.org/data/2.5/weather?'
                    'q={},{}&appid={}'.format(self.city, self.country, API_ID)
        weatherdata = requests.get(url_city).json()  # Call function to get data.
        print(weatherdata)


class MainApplication:
    def __init__(self, master):
        self.getweather = GetWeather('town', 'country')
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text='Coords', width=25,
                                 command=self.getweather.coords)
        self.button1.pack()
        self.frame.pack()


def main():
    root = tk.Tk()
    app = MainApplication(root)
    root.mainloop()

if __name__ == "__main__":
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM