简体   繁体   English

如何在tk.TopLevel()上设置背景图像

[英]How to setup a background image on a tk.TopLevel()

I'm trying to add a background to a tk.TopLevel() window. 我正在尝试向tk.TopLevel()窗口添加背景。

I have succeeded using the same code as follows to add a bakground to a tk.Tk(). 我已经成功使用如下相同的代码将bakground添加到tk.Tk()。 However, the same code doesn't work and leaves me with the default background. 但是,相同的代码不起作用,并且使我处于默认背景。

def add_window_launching():
    #initializing window
    add_window=tk.Toplevel()
    add_window.title("Inventaire Petits Débrouillards")
    add_window.geometry('900x350')
    add_window.resizable(width=False, height=False)

    #Setting background
    raw_image=Image.open("C:/Users/Ordinateur/Desktop/db-update-petits-debrouillards/UI/ajout.png")
    background_image=ImageTk.PhotoImage(raw_image)
    background_label = tk.Label(add_window, image=background_image)

    #Adding widgets
    welcome_text=tk.Label(add_window, text="Text")
    object_description=tk.Label(add_window, text="Description de l'objet :")
    description_entry=tk.Entry(add_window, width=100)
    row=SQL.Entries([description_entry], add_window)
    submit_button=tk.Button(add_window, text="Ajouter", command=row.adding_entry)

    #Organizing window
    background_label.place(x=0, y=0, relwidth=1, relheight=1)
    welcome_text.place(anchor="n", relx=0.5, rely=0.25)
    object_description.place(anchor="nw", relx=0.08, rely=0.5)
    description_entry.place(anchor="ne", relx=0.92, rely=0.5)
    submit_button.place(anchor="n", relx=0.5, rely=0.75)

Here is the result of the execution of the script. 这是脚本执行的结果。 Top window is the main window, bottom window is the TopLevel one. 顶部窗口是主窗口,底部窗口是TopLevel之一。 Backgrounds must be identic. 背景必须相同。 I can't post images because my account is new but you'll find the result i got here . 我无法发布图片,因为我的帐户是新帐户,但是您会在这里找到结果。 Any ideas why it doesn't work ? 任何想法为什么它不起作用?

There is bug in PhotoImage . PhotoImage存在错误。

Garbage Collector removes image from memory when it is assigned to local variable in function and then you can't see image. 当在功能中将图像分配给局部变量后, Garbage Collector会将图像从内存中删除,然后您将看不到图像。

You have to assign image to global variable or to some widget. 您必须将图像分配给全局变量或某些小部件。 It is popular to assign to Label which displays this image: 流行的是分配给显示以下图像的Label

 background_label.image = background_image

Doc: PhotoImage Doc: PhotoImage

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

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