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

Tkinter按钮添加图片时遇「PhotoImage not defined」及「No module named PIL」问题求助

Tkinter按钮添加图片时遇「PhotoImage not defined」及「No module named PIL」问题求助

嘿,我来帮你逐个解决这两个问题~先看看你的代码和遇到的报错:

你的代码:

from tkinter import *

import PIL

count = 0

def click():
    global count
    count+=1
    print(count)

window = Tk()

photo = PhotoImage(file='Flanderson.png')

button = Button(window,
text="Draw A Card",
command=click,
font=("Comic Sans",30),
fg="#00FF00",
bg="black",
activeforeground="#00FF00",
activebackground="black",
state=ACTIVE,
image=photo,
compound='bottom')

button.pack()

window.mainloop()

遇到的问题:

  1. 「PhotoImage not defined」错误
  2. 「No module named PIL」错误,且已通过pip安装Pillow但无效果

一、搞定「PhotoImage not defined」错误

这里分两种情况对应解决:

  • 如果用tkinter原生的PhotoImage:
    理论上from tkinter import *已经导入了这个类,但如果还是报错,大概率是环境或执行顺序的小问题,你可以试试显式导入:

    from tkinter import PhotoImage
    

    另外要注意:tkinter原生的PhotoImage只支持PNG和GIF格式,如果你的图片是JPG/JPEG这类格式,原生工具识别不了,这时候就得靠PIL来帮忙了。

  • 如果需要处理非PNG/GIF的图片:
    你只写import PIL是没用的,得显式导入PIL里负责图片处理的模块,修改导入部分:

    from PIL import Image, ImageTk
    

    然后创建图片对象的代码也要改成PIL的写法:

    photo = ImageTk.PhotoImage(Image.open('Flanderson.png'))
    

    额外提个坑:如果PhotoImage是局部变量,容易被Python的垃圾回收机制清掉,导致按钮上不显示图片。你的代码里photo是全局变量没问题,但如果后续把这部分逻辑放到函数里,记得给按钮绑定个引用,比如button.image = photo。


二、解决「No module named PIL」错误(装了Pillow还是没用)

Pillow是PIL的官方替代分支,安装后要通过from PIL import ...导入,但如果还是报错,大概率是这几个原因:

  • Python和pip版本不匹配:比如你的系统同时装了Python2和Python3,用pip install pillow可能装到了Python2环境里,但你运行代码用的是Python3。这时候可以明确指定版本安装:
    • 给Python3装:pip3 install pillow
    • 或者用python -m pip install pillow(确保python命令指向你用的Python版本)
  • 虚拟环境没激活:如果你用了虚拟环境开发,必须先激活对应环境再装Pillow,否则包会装到全局环境里,虚拟环境内的代码还是找不到。
  • IDE解释器配置错了:比如VS Code、PyCharm这类工具,可能没选中你装了Pillow的Python解释器,去IDE的设置里切换一下就行。

最后给你贴一份修改后的完整代码示例:

from tkinter import *
from PIL import Image, ImageTk

count = 0

def click():
    global count
    count += 1
    print(count)

window = Tk()

# 用PIL加载图片,支持更多格式
image = Image.open('Flanderson.png')
photo = ImageTk.PhotoImage(image)

button = Button(window,
                text="Draw A Card",
                command=click,
                font=("Comic Sans", 30),
                fg="#00FF00",
                bg="black",
                activeforeground="#00FF00",
                activebackground="black",
                state=ACTIVE,
                image=photo,
                compound='bottom')
button.pack()

# 绑定图片引用,防止被垃圾回收
button.image = photo

window.mainloop()

备注:内容来源于stack exchange,提问作者Padron_62

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 08:39:08