首页 > 解决方案 > TKinter 背景调整器 + 按钮/标签

问题描述

当 bg 图像适合屏幕的调整大小时,我正在尝试在背景上设置带有壁纸的 tkinter gui 屏幕,我从这里获取了代码..但问题是当我尝试在其上放置按钮或其他标签时,壁纸仍然停留在顶部,我看不到它们。

这里的代码:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
root.title("Title")
root.geometry("800x600")

class Example(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.configure(background="black")
        self.grid(sticky=N+S+E+W)
        self.image = Image.open("bg.jpg")
        self.img_copy= self.image.copy()
        self.background_image = ImageTk.PhotoImage(self.image)

        self.background = Label(self, image=self.background_image)
        self.background.grid(row =0, column =0,sticky="nsew")
        self.background.grid_rowconfigure(0, weight=1)
        self.background.grid_columnconfigure(0, weight=1)

        self.master = master
        self.master.bind('<Configure>', self._resize_image)

        # create a button
        self.button= Button(root, text="EXIT", width=4).grid(row=3, column=1, sticky=N+S+E+W)

    def _resize_image(self,event):
        new_width = self.master.winfo_width()
        new_height = self.master.winfo_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)

e = Example(root)
e.grid(row =0, column =0,sticky="nsew")
e.grid_rowconfigure(0, weight=1)
e.grid_columnconfigure(0, weight=1)

root.mainloop()

标签: pythonpython-3.xtkinter

解决方案


您需要使用place()放置背景图像,以便它不会干扰同一父级中的其他小部件。

以下是基于您的代码的简化示例:

from tkinter import *
from PIL import Image, ImageTk

class Example(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.configure(background="black")

        self.image = Image.open("bg.jpg")

        # label for the background image
        self.background = Label(self)
        self.background.place(x=0, y=0)

        self.bind('<Configure>', self._resize_image)

        # create a button
        self.button = Button(self, text="EXIT", width=4)
        self.button.grid(row=3, column=1, sticky=N+S+E+W, padx=50, pady=50)

    def _resize_image(self,event):
        if event.widget is self:
            # resize background image to fit the frame size
            image = self.image.resize((event.width, event.height))
            self.background_image = ImageTk.PhotoImage(image)
            self.background.configure(image=self.background_image)

root = Tk()
root.title("Title")
root.geometry("800x600")

e = Example(root)
e.pack(fill=BOTH, expand=1)

root.mainloop()

推荐阅读