Я опробую Tkinter с Openweathermap API для прогноза погоды на несколько дней. В первой функции: «def format_response (weather)», если я использую print (final_str), результат будет хорошим для Python Shell, но на этикетке ничего не показано. Если я использую return (final_str), метка показывает только один день погоды. Как мне go показать весь результат на этикетке?
Спасибо в advnace.
import tkinter as tk
from tkinter import font
from PIL import ImageTk, Image
import requests
from datetime import datetime
HEIGHT = 700
WIDTH = 700
def format_response(weather):
for i in range(10):
dt_txt = weather['list'][i]['dt']
date = (datetime.fromtimestamp(dt_txt)).strftime('%d-%b-%Y %H:%M:%S')
desc = weather['list'][i]['weather'][0]['description']
temp_min = weather['list'][i]['main']['temp_min']
temp_max = weather['list'][i]['main']['temp_max']
final_str = 'Date: %s \nConditions: %s \nMin.Temperature(Celsius): %s\nMax.Temperature(Celsius): %s' %(date, desc, temp_min, temp_max)
return(final_str)
def get_weather(city):
api_key = 'a4aa5e3d83ffefaba8c00284de6ef7c3'
url = 'https://api.openweathermap.org/data/2.5/forecast' # can switch between forecast and weather
params = {'APPID': api_key, 'q': city, 'units': 'metric'}
response = requests.get(url, params = params)
weather = response.json()
label['text'] = format_response(weather)
root = tk.Tk()
# CANVAS SIZE
canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()
# BACKGROUND
background_image = ImageTk.PhotoImage(Image.open("D:/Documents/Python/GUI/Weather App/beach.png"))
background_label = tk.Label(root, image = background_image)
background_label.place(relwidth = 1, relheight = 1)
# FRAME, UPPER
frame = tk.Frame(root, bg = '#b1cfff', bd = 5)
frame.place(relx = 0.5, rely = 0.15, relwidth = 0.80, relheight = 0.05, anchor = 'n')
# use value '1' to fill entire box
# ENTRY/INPUT
entry = tk.Entry(frame, bg='#fce300', font = 40)
entry.place(relx = 0.0, rely = 0, relwidth = 0.75, relheight = 1)
# BUTTON
button = tk.Button(frame, text = "SEARCH", font = 40, bg = 'black', fg = 'yellow', command = lambda: get_weather(entry.get()))
button.place(relx = 0.758, rely = 0, relwidth = 0.24, relheight = 1)
# FRAME, LOWER
lower_frame = tk.Frame(root, bg = '#b1cfff', bd = 5)
lower_frame.place(relx = 0.5, rely = 0.25, relwidth = 0.80, relheight = 0.6, anchor = 'n')
# LABEL, FRAME, LOWER
label = tk.Label(lower_frame, font = ('courier new',10), bg = '#fce300', anchor = 'nw', justify = 'left')
label.place(relwidth = 1, relheight = 1)
root.mainloop()