3

I am trying to place two image buttons on my image background in a certain position, but my buttons are not appearing. I think their images are behind the background.

I tried to use place and pack, both did not work. What could be the problem?

from tkinter import* import tkinter as tk import settings class Application(Frame): def __init__ (self, master): Frame.__init__(self,master) self.grid() self.create_widgets() def create_widgets(self): button1 = PhotoImage(file ="button1.gif") button2 = PhotoImage(file ="button2.gif") settings_button = Button(self, image = button1, command = self.mult_command, width = 15) settings_button.place(x=1, y=1) rules_button = Button(self, image = button2, command = self.the_rules, width = 15) rules_button.place(x=50, y=50) def main_code(): window = Tk() window.title("The Bouncer") bg_image = PhotoImage(file ="pic.gif") x = Label (image = bg_image) x.image = bg_image x.place(x = 0, y = 0, relwidth=1, relheight=1) window.geometry("600x300") app = Application(window) window.mainloop() main_code() 

thanks

2 Answers 2

5

It is likely that your image is being garbage collected before it is displayed. This is a common Tkinter gotcha. Try changing the lines:

button1 = PhotoImage(file ="button1.gif") button2 = PhotoImage(file ="button2.gif") 

to

self.button1 = PhotoImage(file ="button1.gif") self.button2 = PhotoImage(file ="button2.gif") 

and use

settings_button = Button(self, image = self.button1, command = self.mult_command, width = 15) 

etc.

This should keep a reference to your image, stopping it from getting garbage collected.

Sign up to request clarification or add additional context in comments.

1 Comment

yes that did the trick for me
1

In addition to keeping a reference to the image, you have a problem with this line:

self.grid() 

in the __init__ method of Application. It's gridding the Frame into the window, but since nothing is ever packed or gridded into the frame, it doesn't ever expand past a little, tiny frame, so you just don't see the Buttons inside it. A simple fix here would be the pack method, with arguments to fill the window and expand when needed:

self.pack(fill=BOTH, expand=1) 

4 Comments

Ok. I changed grid() to pad(), and it seems to be better now. I can see my background image and my buttons, but not the buttons on top of the BG image. Do you kknow how I can fix this?
Move the label with the bg image into the Frame. After you pack the frame, place the bg image, then create the widgets.
Sorry I still didnt get it.
You're not assigning the Label that contains the image to a parent. If you create the Label within the constructor of the Application class, you can put it in the same Frame as the buttons, and draw it under the buttons.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.