python 通过tkinter向按钮添加图像

rslzwgfq  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(192)

这是密码

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()

因此,我尝试下载并将图像添加到我的按钮中,但也发生“未定义PhotoImage”错误,“没有名为PIL的模块”
我通过pip安装了Pillow,但没有任何变化

eimct9ow

eimct9ow1#

您将获得"PhotoImage not defined",因为PhotoImage类仅支持PGM,PPM,GIF,PNG格式的图像格式。由于您使用的是PNG,请确保您使用的是最新版本的Tkinter。因此,您应该编写:

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

如果你想使用其他格式,你可以使用这个:

Image.open("Flanderson.jpg")
render = ImageTk.PhotoImage(load)

所以最终的代码将是:

from tkinter import *
from PIL import ImageTk, Image

count = 0

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

window = Tk()

load = Image.open("Flanderson.jpg")
render = ImageTk.PhotoImage(load)

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()

对于"No module named PIL",请确保您安装了pillow模块。如果它不工作,请尝试重新启动您的软件,并在命令提示符下键入pip install Pillow再次安装Pillow模块。

相关问题