coder
coder

Reputation: 1941

Image on a button

I expect the same output for both of the scripts below.

But I don't get the image on the button when I execute Script 1. However, Script 2 works well.

Script 1

from Tkinter import *
  class fe:
    def __init__(self,master):
      self.b=Button(master,justify = LEFT)
      photo=PhotoImage(file="mine32.gif")
      self.b.config(image=photo,width="10",height="10")
      self.b.pack(side=LEFT)
root = Tk()
front_end=fe(root)
root.mainloop()

Script 2

from Tkinter import *
root=Tk()
b=Button(root,justify = LEFT)
photo=PhotoImage(file="mine32.gif")
b.config(image=photo,width="10",height="10")
b.pack(side=LEFT)
root.mainloop()

Upvotes: 28

Views: 88405

Answers (5)

Bryan Oakley
Bryan Oakley

Reputation: 385830

The only reference to the image object is a local variable. When __init__ exits, the local variable is garbage collected so the image is destroyed. In the second example, because the image is created at the global level it never goes out of scope and is therefore never garbage collected.

To work around this, save a reference to the image. For example, instead of photo use self.photo.

Upvotes: 39

nda
nda

Reputation: 561

Unrelated answer, but this is the answer I was looking for when I first came here. Use this to resize the image before adding it to the button.

from PIL import Image, ImageTk

image = Image.open("path/to/image.png")
image = image.resize((25, 25), Image.ANTIALIAS)
self.reset_img = ImageTk.PhotoImage(image)
self.button = tk.Button(frame, image=self.reset_img)

Upvotes: 1

Mawty
Mawty

Reputation: 464

from tkinter import *

root= Tk()

btnPlay = Button(root)
btnPlay.config(image=imgPlay, width="30", height="30")
btnPlay.grid(row=0, column=0)

root.mainloop()

Upvotes: 0

Saurabh Chandra Patel
Saurabh Chandra Patel

Reputation: 13586

logo = PhotoImage(file = 'mine32.gif')
small_logo = logo.subsample(5, 5)
self.b.config(image = small_logo , compound = LEFT )

Upvotes: 1

user8777433
user8777433

Reputation:

its work

x1=Button(root)
photo=PhotoImage(file="Re.png")
x1.config(image=photo,width="40",height="40",activebackground="black"
,bg="black", bd=0,command=sil)
x1.place(relx=1,x=5, y=-5, anchor=NE)

but this is useless

def r():
    x1=Button(root)
    photo=PhotoImage(file="Re.png")
    x1.config(image=photo,width="40",height="40",activebackground="black",
    bg="black", bd=0,command=sil)
    x1.place(relx=1,x=5, y=-5, anchor=NE)

r()

Upvotes: 1

Related Questions