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

课程期末项目:货币转换器图片不显示问题求助

解决CustomTkinter中PIL图像无法显示的问题

问题核心

你遇到的图片不显示问题,根源是Tkinter PhotoImage的垃圾回收特性:Python会自动回收没有被持久引用的ImageTk.PhotoImage对象,导致CustomTkinter的标签控件无法找到图像数据,最终显示空白。

解决方法

给图像对象添加持久引用,同时确保图片路径正确:

  • 保留图像引用:把ImageTk.PhotoImage对象赋值给标签的自定义属性(比如photo_label.photo),避免被垃圾回收;
  • 验证路径:确认money.png和你的Python脚本在同一目录,或者使用绝对路径(例如C:/projects/money.png)。

修改后的代码

import customtkinter
from tkinter import *
from forex_python.converter import CurrencyRates
from PIL import Image, ImageTk

app = customtkinter.CTk()
app.config(bg="#202630")
app.geometry("400x450")
app.title("Currency Converter")

# 加载图片(确保路径正确)
img_path = "money.png"
img_pil = Image.open(img_path)
img = ImageTk.PhotoImage(img_pil)

# 创建标签并绑定图像引用
photo_label = customtkinter.CTkLabel(app, fg_color="#202630", image=img)
photo_label.photo = img  # 关键:保留图像引用,防止被回收
photo_label.place(x=0, y=0)

app.iconphoto(False, img)
app.mainloop()

额外提示

如果图片尺寸过大,可使用PIL的resize方法调整大小后再转换:

img_pil = Image.open(img_path).resize((400, 150), Image.Resampling.LANCZOS)

内容的提问来源于stack exchange,提问作者Angelo Hiroki Alburo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:32:13