-1

I am creating a weather app that includes an ImageFrame and CurrentWeatherFrame. I am having issues getting ImageFrame to appear when I run my script. I am only seeing the CurrentWeatherFrame. Can someone help me figure out what is causing this issue?

import tkinter as tk
import os
from tkinter import ttk
from PIL import Image, ImageTk
from Weather import WeatherPredictions as wp

class ImageFrame(tk.Frame):
    def __init__(self, container):
        super().__init__(container)
        self.columnconfigure(0, weight=1)
        self.__create_widgets()

    def __create_widgets(self):
        os.chdir(r'C:\Users\milos\OneDrive\Dokumenty\GitHub\Weather-forecast\images')
        img = Image.open("weather.png")
        smaller_image = img.resize((300,300), Image.LANCZOS)#ANTIALIS
        img1 = ImageTk.PhotoImage(smaller_image)
        tk.Label(self, image = img1).grid(column=0, row=0)

class CurrentWeatherFrame(tk.Frame):
    def __init__(self, container):
        super().__init__(container)
        self.__create_widgets()

    def __create_widgets(self):
        current_weather = wp.current_weather()
        place_name,weather_code,temperature,precipitation_probability,windspeed = current_weather[0],current_weather[1], current_weather[2],current_weather[3],current_weather[4]
        tk.Label(self, text=place_name).grid(row=0, column=0)

class app(tk.Tk):
    def __init__(self):
        super().__init__()
        os.chdir(r'C:\Users\milos\OneDrive\Dokumenty\GitHub\Weather-forecast\images')
        self.title('Weather forecast')
        self.iconbitmap("icon.ico")
        self.geometry('800x600+50+50')
        self.resizable(0, 0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1,weight=1)
        self.__create_widgets()
    
    def __create_widgets(self):
        current_weather_frame = CurrentWeatherFrame(self)
        current_weather_frame.grid(column = 0, row = 0)
        image_frame = ImageFrame(self)
        image_frame.grid(column = 1, row = 0, sticky='e')

if __name__ == "__main__":
   app1 = app()
   app1.mainloop()
Ravs0nek
  • 1
  • 1

1 Answers1

0

This is a subtle bug in tkinter. tk.Label does not grab a reference to the PhotoImage, so when __create_widgets ends, the photo is deleted. Just use self.img1 instead of img1.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30