You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

天气App中ImageFrame组件无法显示问题求助

天气应用中ImageFrame无法显示的问题排查与修复

核心问题

你遇到的ImageFrame不显示的主要原因是Tkinter PhotoImage对象被垃圾回收:在ImageFrame.__create_widgets()方法里,img1是局部变量,方法执行完毕后会被Python自动回收,导致Label找不到图片资源,最终整个ImageFrame因无可见内容而"消失"。

修复方案

  1. 将PhotoImage对象绑定为ImageFrame的实例属性,避免被垃圾回收机制清理
  2. 调整布局参数,让ImageFrame更合理地填充分配的单元格

修改后的完整代码

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)
        # 将img1保存为实例属性,防止被垃圾回收
        self.img1 = ImageTk.PhotoImage(smaller_image)
        tk.Label(self, image=self.img1).grid(column=0, row=0)
        # 让Label填充整个ImageFrame单元格
        self.grid_rowconfigure(0, weight=1)

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)
        # 让行分配权重,让两个Frame垂直填充窗口
        self.grid_rowconfigure(0, weight=1)
        self.__create_widgets()
    
    def __create_widgets(self):
        current_weather_frame = CurrentWeatherFrame(self)
        # 让CurrentWeatherFrame填充左侧单元格
        current_weather_frame.grid(column=0, row=0, sticky='nsew')
        image_frame = ImageFrame(self)
        # 让ImageFrame填充右侧单元格
        image_frame.grid(column=1, row=0, sticky='nsew')

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

额外说明

  • 除了保存PhotoImage为实例属性,还添加了grid_rowconfigure和sticky='nsew'参数,让两个Frame能更好地适配窗口大小,避免布局错位。
  • 如果图片仍无法显示,可检查weather.png是否在指定目录下,或改用绝对路径读取图片。

内容的提问来源于stack exchange,提问作者Ravs0nek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:43:10