Как вызвать функцию запуска из класса - PullRequest
0 голосов
/ 24 июня 2019

Я учусь пользоваться классами и хочу позвонить в мой GetWeather класс из другого MainApplication класса.

После вызова GetWeather.coords я хочу начать с функции, которая получает необходимые данные.

Ниже мой код:

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()

Ответы [ 2 ]

0 голосов
/ 24 июня 2019

Ничто не мешает вам сделать это, но вы должны убедиться, что функция имеет необходимую информацию.Поскольку coords() является методом класса GetWeather, это можно сделать, просто сохранив значения, переданные ему при создании экземпляра класса, а затем используя его.

Ниже приведен пример кода, показывающийкак это сделать, и она будет вызывать функцию для извлечения данных при каждом нажатии 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()
0 голосов
/ 24 июня 2019

Чтобы создать экземпляр класса, назовите его так, как если бы это была функция, которая, как оказалось, возвращала объект GetWeather.

Кроме того, аргумент tkinter.Button 'command должно быть чем-то, что он может вызвать снова, то есть вы должны передать ему функцию, которая еще не была вызвана.Обратите внимание на пропущенные скобки после GetWeather('town','country').print_coords.

Вот ваш фиксированный код:

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...