python - 如何将图像插入按钮?

标签 python python-3.x tkinter python-3.3 python-imaging-library

我正在执行以下代码

import tkinter
import tkinter.messagebox
import random
from PIL import Image

item = tkinter.Button(root,
                text=color,
                width=20,
                height=10,
                relief='raised',
                borderwidth=5,
                bg=color
            )

original = Image.open('images/img1.gif')
ph_im = Image.PhotoImage(original)
item.config(image=ph_im)
item.pack(side='left')

我正在使用 Python33 的 Pillow。我试图将图像插入按钮,但返回此错误消息:

Traceback (most recent call last):   File "C:\Python33\projects\svetofor\index2.py", line 94, in <module>
    Application(root)   File "C:\Python33\projects\svetofor\index2.py", line 20, in __init__
    self.make_widgets()   File "C:\Python33\projects\svetofor\index2.py", line 50, in make_widgets
    ph_im = Image.PhotoImage(original) AttributeError: 'module' object has no attribute 'PhotoImage'

最佳答案

PhotoImage位于 PIL.ImageTk模块。

import tkinter
import tkinter.messagebox
import random
from PIL import Image, ImageTk # <---

root = tkinter.Tk()
color = 'white'

item = tkinter.Button(root,
                text=color,
                width=20,
                height=10,
                relief='raised',
                borderwidth=5,
                bg=color
            )

original = Image.open('images/img1.gif')
ph_im = ImageTk.PhotoImage(original) # <----------
item.config(image=ph_im)
item.pack(side='left')
root.mainloop()

enter image description here

关于python - 如何将图像插入按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21649436/

相关文章:

python - 在多处理 pool.starmap 中传递字符串列表时出错

python - 如何更改 CharField 选择列表行为

python3多进程共享numpy数组(只读)

python - 除以零错误输入到Tkinter消息中供计算器使用

python - 如何让 python 循环记住每个值?

python - 根据python中的自定义函数聚合数据框中的每一列

python tkinter Canvas 不调整大小

python - 使用 Tk Spinbox 小部件后,Matplotlib FigureCanvasTkAgg 未检测到按键

python - 支持回推的迭代器

python - 神经网络模型可以使用加权平均(和)平方误差作为损失函数吗?