简体   繁体   English

在 Tkinter 中将其用作背景时不显示图像

[英]Image not displayed when using it as a background in Tkinter

Hy!嗨! I am trying to use an image as a background in a GUI created in Tkinter.我试图在 Tkinter 中创建的 GUI 中使用图像作为背景。 It works fine with the same code on a different frame in this project, but it doesn't want to work in a different frame.在这个项目的不同框架上使用相同的代码可以正常工作,但它不想在不同的框架中工作。 I get no error, the frame is just blank.我没有错误,框架只是空白。 Thank you for your help!感谢您的帮助!

Here I can use the picture as a background just fine:在这里我可以用图片作为背景就好了:

def main_screen():
global screen
screen = Tk()
screen.geometry("600x750")
screen.configure(background="#022140")
screen.title("Hermes")
filename = PhotoImage(file="background.png")
filename_small = filename.subsample(2, 2)
background_label = Label(image=filename_small)
background_label.place(x=1, y=1, relwidth=1, relheight=1)
login_button = Button(text="Login", bg="#022140", height="2", width="30", command=login,
                      highlightbackground='#494B68')
screen.mainloop()

But here it won't work:但在这里它不起作用:

def login_sucess():
    global screen3
    screen3 = Toplevel(screen)
    screen3.geometry("500x400")
    filename = PhotoImage(file="main_theme.png")
    filename_small = filename.subsample(2, 2)
    background_label = Label(screen3, image=filename_small)
    background_label.place()

Thank you for your help!感谢您的帮助!

It should be quite simple.这应该很简单。 When you're working with images in tkinter you always need to set a reference to that image on the widget you used it on.当您在 tkinter 中处理图像时,您始终需要在使用它的小部件上设置对该图像的引用。 In other words do something like this:换句话说,做这样的事情:

from tkinter import Tk,Label,PhotoImage

root = Tk()
img = PhotoImage(file='background.png')
small_img=img.subsample(2, 2)
background_label = Label(root, image=small_img)
background_label.img=img
background_label.place(x=0, y=0, relheight=1, relwidth=1)
root.mainloop()

Especially when you create the Label holding the image in a functions scope or something similar it's important to set that reference since the variable to that Labels instance will be gone after the function call ends.特别是当您在函数作用域或类似的东西中创建保存图像的标签时,设置该引用很重要,因为在函数调用结束后,该标签实例的变量将消失。

PS: To be more clear about master widgets and for small performance improvements always give a widget a master widget when initializing it. PS:为了更清楚地了解主小部件和小的性能改进,在初始化时总是给小部件一个主小部件。 I know tkinter also automatically assigns the last created Tk instance as master itself but a) does that need unneccesary computing power and b) is it easier to keep track of what widget is a child of another and so on.我知道 tkinter 也会自动将最后创建的 Tk 实例分配为 master 本身,但是 a) 是否需要不必要的计算能力,b) 是否更容易跟踪哪个小部件是另一个小部件的子部件等等。 ;) ;)

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

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