Search code examples
python-3.xtkinterphotoimage

Tkinter: Buttons can't be added on resizable PhotoImage


Buttons can't be added on resizable image label in Tkinter. I am trying to add a resizable image that is easily showing up. Also, I am trying to add buttons on the top of it which seems to me as an issue.

Here's the code:

from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk

root = Tk()
root.title("Speaker Recognition")
root.geometry('1280x800+0+0')

def resize_image(event):
    new_width = event.width
    new_height = event.height
    image = copy_of_image.resize((new_width, new_height))
    photo = ImageTk.PhotoImage(image)
    label.config(image = photo)
    label.image = photo 

## Resizable Image

image = Image.open('speakerid.gif')
copy_of_image = image.copy()
photo = ImageTk.PhotoImage(image)
label = Label(root, image=photo)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.bind('<Configure>', resize_image)
label.pack(fill=BOTH, expand = YES)

##Adding Buttons

train_button = Button(root, bg="red", text='Train the machine')
train_button.place(x=0, y=0, relwidth=1, relheight=1)
train_button.pack()
test_button = Button(root, bg="red", text='Test the machine')
test_button.place(x=0, y=0, relwidth=1, relheight=1)
test_button.pack()
quit = Button(root, bg="red", text="Quit", command=root.destroy)
quit.place(x=0, y=0, relwidth=1, relheight=1)
quit.pack()
root.mainloop()

Any idea how to fix this?


Solution

  • You cannot both place and pack widgets. In this case, just place everything. You have the image label filling the container at the lower z-order and if you then place your labels and discard the pack() method call they should appear fine as their z-order is higher than the label. Otherwise lower and tkraise can be used to adjust the ordering so the buttons appear on top of the label.