繁体   English   中英

如何在 tkinter python 的框架中添加背景图像? 我想要一个图像而不是背景颜色

[英]How to add background image to the frame in tkinter python? Instead of background color I want an image

需要添加图片作为框架背景,退出按钮必须在图片上。我尝试了一些代码,但图片出现如上图和图片下方的框架。

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


root = Tk()
root.title("Sign In")
root.geometry("600x420")

class one:

    def __init__(self, root):
        self.root = root
        self.frame = Frame(self.root, bg="light blue", width=800, height=400)
        root.geometry("800x400")
        self.header = Label(self.root, bg="blue", fg="white", font=("Times New Roman", 30, "bold"))
        self.header.pack(fill=X)
        self.heading = Label(self.root, text="First One", fg="white", bg="blue", font=("Times New Roman", 30, "bold"))
        self.heading.place(x=10, y=0)
        self.q = Button(self.frame, text="Quit", bg="brown", fg="white", font=("Times New Roman", 10), command=self.root.destroy)
        self.q.place(x=650, y=320, width=120, height=20)
        self.frame.pack()

obj = one(root)
root.mainloop()

在 Tkinter 中,您可以通过添加标签作为框架父级来向框架添加背景图像。 使用 PIL 设置标签背景图像并将框架背景设置为空字符串。

试试这个代码。

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

root = Tk()
root.title("Sign In")
root.geometry("600x420")

class one:

    def __init__(self, root):
        self.root = root
        self.img = ImageTk.PhotoImage(Image.open("bgredgrad.png"))  # label image (frame background)
        self.label = Label(self.root, image = self.img, width=800, height=400)  # frame parent
        
        self.frame = Frame(self.label, bg="", width=800, height=400)  # main widget, clear background
        self.frame.place(x=0, y=0, width=800, height=400)   # required for correct z-index
        root.geometry("800x400")
        self.header = Label(self.root, bg="brown", fg="white", font=("Times New Roman", 30, "bold"))
        self.header.pack(fill=X)
        self.heading = Label(self.root, text="First One", bg="brown", fg="white", font=("Times New Roman", 30, "bold"))
        self.heading.place(x=10, y=0)
        self.q = Button(self.frame, text="Quit", bg="brown", fg="white", font=("Times New Roman", 10), command=self.root.destroy)
        self.q.place(x=650, y=320, width=120, height=20)
        self.label.pack()  # pack bottom widget

obj = one(root)
root.mainloop()

输出(我的背景)

背景图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM