Tkinter:无法在可调整大小的 PhotoImage 上添加按钮

Tkinter: Buttons can't be added on resizable PhotoImage

无法在 Tkinter 中将按钮添加到可调整大小的图像标签上。我正在尝试添加一个易于显示的可调整大小的图像。另外,我正在尝试在它的顶部添加按钮,这在我看来是个问题。

代码如下:

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

知道如何解决这个问题吗?

您不能同时放置和打包小部件。在这种情况下,只需放置所有内容。您的图像标签在较低的 z-order 处填充容器,如果您随后放置标签并丢弃 pack() 方法调用,它们应该看起来很好,因为它们的 z-order 高于标签。否则可以使用 lower 和 tkraise 来调整顺序,使按钮出现在标签的顶部。