首页 > 解决方案 > 如何将按钮放在图像顶部?(tkinter)

问题描述

如何将按钮放在图像上并将其保持在窗口的中心?代码工作正常,但按钮在图像下方,我无法单击它

from tkinter import Frame, Tk, Label, Button
from PIL import Image, ImageTk

class Example(Frame):
    def __init__(self, master, *pargs):
        Frame.__init__(self, master, *pargs)

        self.image = Image.open("folder\\file.gif")
        self.img_copy= self.image.copy()

        self.background_image = ImageTk.PhotoImage(self.image)

        self.background = Label(self, image=self.background_image)
        self.background.pack(fill="both", expand="YES")
        self.background.bind('<Configure>', self._resize_image)

    def _resize_image(self,event):

        new_width = event.width
        new_height = event.height

        self.image = self.img_copy.resize((new_width, new_height))

        self.background_image = ImageTk.PhotoImage(self.image)
        self.background.configure(image =  self.background_image)

root = Tk()
root.title("Title")
root.geometry("600x600")
root.configure(background="black")

e = Example(root)
e.pack(fill="both", expand="YES")

btn=Button(root,text="Hello World").pack()

root.mainloop()

标签: pythonpython-3.xtkinter

解决方案


我不知道这是否是您真实应用程序的正确解决方案,但对于问题中的代码,最简单的解决方案是使用place. 您可以使用place相对位置来保持一个小部件在另一个小部件中居中。

place作为通用布局管理器也不是最好的,但对于非常具体的用例,它是适合这项工作的工具。在以下示例中,使用、和将按钮放置在Example框架的中心。该参数指定相对坐标相对于哪个小部件。relxrelyanchorin_

btn=Button(root,text="Hello World")
btn.place(in_=e, relx=.5, rely=.5, anchor="c")

推荐阅读