python - 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()
解决方案
您需要使用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()
推荐阅读
- python - 使用变量名的嵌套字典项的 Django 模板语法
- json - Xamarin 形式。无法在列表中显示 json 对象
- json - 将数组转换为以 ID 作为索引的 JSON (MongoDB / Express)
- sql - 连接两个表,其中一些列合并,其他列必须为空
- javascript - jQuery - 重定向到从 URL 加载()内容后如何获取最终链接?
- c# - c#UserControl构造函数不会按预期抛出异常
- graph - 如何在 m 个节点之间生成 n 条边
- docker - 来自 Docker 容器的空响应
- java - 动态改变按钮主题
- javascript - django 视图中给出的 json。作为json发送到模板的js