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

求助:Tkinter加载background.png遇_tkinter.TclError错误

解决Tkinter无法识别PNG图片的问题

问题根源

你碰到的_tkinter.TclError: couldn't recognize data in image file "background.png",主要是因为Tkinter原生的PhotoImage支持的图片格式非常有限——仅能处理GIF、PGM、PPM,部分环境下对PNG的支持不完善;另外也可能是图片损坏、路径不对导致的。

靠谱的解决办法

1. 用Pillow库替代原生加载(最推荐)

Pillow是Python的图片处理库,支持几乎所有主流图片格式,步骤简单:

  • 先安装库:
pip install pillow
  • 修改代码,替换图片加载部分:
from PIL import Image, ImageTk
import tkinter as tk
from tkinter import Button

root = tk.Tk()
root.title("Broken Rootery")
root.attributes("-fullscreen", True)
root.config(bg="black")

close = Button(root, text="Quit", fg="white", bg="black", font="System", bd=0, command=root.quit)
close.pack(side=tk.BOTTOM)

# 用Pillow打开图片,转成Tkinter能用的格式
img = Image.open('background.png')
tk_img = ImageTk.PhotoImage(img)

lab = tk.Label(root, image=tk_img)
lab.pack()
# 重要:必须保留图片对象的引用,不然Python垃圾回收会把它清掉,图片显示不出来
lab.image = tk_img

root.mainloop()

2. 检查图片和路径

  • 确认background.png是标准PNG:用画图、Photoshop重新导出一遍,避免文件损坏
  • 确认路径正确:如果图片不在脚本同目录,就用绝对路径,比如:
# 把路径换成你实际的图片路径
img = tkinter.PhotoImage(file=r'C:\Users\User\Desktop\BS1\background.png')

3. 升级Tcl/Tk(不推荐)

要是非要用原生PhotoImage,可以试试升级系统的Tcl/Tk版本,部分新版本对PNG支持更好,但这个方案兼容性差,不如Pillow省心。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:20:32