How to insert an image into a button?

こ雲淡風輕ζ 提交于 2019-12-11 08:47:01

问题


I'm executing the following code

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

I am using Pillow for Python33. I'm trying to insert an image into a button, but returns this error message:

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:


PhotoImage is in PIL.ImageTk module.

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



来源:https://stackoverflow.com/questions/21649436/how-to-insert-an-image-into-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!