Image & Text button – no image appears – tkinter

Question:

It’s my first post here, I also have a puzzlement about the code below.
I don’t have the image displayed next to the text, the button is properly displayed (p.s : why the height and width have to be adjusted again, for example the button without the picture has width = 22 and height = 2, when I put the picture to be visible I have 200 by 200, well it can be a bit smaller), I have the text displayed, but the picture is missing…Could it be from .grid?

bl_logo = Image.open('img/balance.png')
bl_logo = bl_logo.resize((25,25), Image.ANTIALIAS)
balance_img = ImageTk.PhotoImage(bl_logo)
buttons_frame = tk.Frame(main_frame, bg = "#004d4d")
balance_btn = tk.Button(buttons_frame, image = balance_img, compound = tk.LEFT, text = 'BALANCE', font = ('Bebas NEUE', 20), width = 220, height = 200)
balance_btn.grid(row = 0, column = 0, sticky = tk.W, padx = 10, pady = (60,40)
Asked By: C Marian

||

Answers:

You have to save the balance_img in the widget class to prevent it from the garbage collector.

add this line balance_btn.image = balance_img

bl_logo = Image.open('img/balance.png')
bl_logo = bl_logo.resize((25,25), Image.ANTIALIAS)
balance_img = ImageTk.PhotoImage(bl_logo)
buttons_frame = tk.Frame(main_frame, bg = "#004d4d")
balance_btn = tk.Button(buttons_frame, image = balance_img, compound = tk.LEFT, text = 'BALANCE', font = ('Bebas NEUE', 20), width = 220, height = 200)
balance_btn.image = balance_img
balance_btn.grid(row = 0, column = 0, sticky = tk.W, padx = 10, pady = (60,40)

I already answer this question’s answer to another user.

Answered By: codester_09
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.