Home > OS >  Adding image to button via tkinter
Adding image to button via tkinter

Time:01-02

This is the code...

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

So I am trying to download add an image to my button but "PhotoImage not defined" error occurs also "No module named PIL"

I installed Pillow via pip but nothing changes

CodePudding user response:

You are getting "PhotoImage not defined" because you might be using older version of Tkinter. And also PhotoImage class only supports PGM, PPM, GIF, PNG format image formats. so you should write:

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

and if you want to use other format, you can use this:

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

so the final code will be:

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

for "No module named PIL" make sure you installed the pillow module. If it doesn't work try to restart your software and install Pillow module again by typing pip install Pillow in command prompt I was also having this problem earlier.

  • Related