如何将图像插入按钮?

时间:2014-02-08 17:36:37

标签: python python-3.x tkinter python-3.3 pillow

我正在执行以下代码

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

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

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'

1 个答案:

答案 0 :(得分:1)

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