【问题标题】:How to add background image to the frame in tkinter python? Instead of background color I want an image如何在 tkinter python 中将背景图像添加到框架中?我想要一个图像而不是背景颜色
【发布时间】:2020-10-09 12:23:09
【问题描述】:

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

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

【问题讨论】:

  • 嗯,我不认为它可以放在框架上,而是尝试Canvas?
  • 您在询问之前是否尝试过搜索此站点?背景图片有很多问题。

标签: python tkinter frame tkinter-canvas


【解决方案1】:

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

输出(我的背景)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 2019-02-28
    • 2019-01-19
    • 1970-01-01
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    相关资源
    最近更新 更多