【问题标题】:Image not displayed when using it as a background in Tkinter在 Tkinter 中将其用作背景时不显示图像
【发布时间】:2020-02-27 20:10:47
【问题描述】:

喂! 我正在尝试在 Tkinter 中创建的 GUI 中使用图像作为背景。在这个项目的不同框架上使用相同的代码可以正常工作,但它不想在不同的框架中工作。我没有错误,框架只是空白。 感谢您的帮助!

这里我可以用图片做背景就好了:

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

但在这里它不起作用:

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

感谢您的帮助!

【问题讨论】:

  • 对于第一种情况,screen.mainloop()main_screen() 内部调用了吗?如果否,则不应显示背景图片(与第二种情况相同)。
  • 我试过了,没有任何改变。
  • 你尝试了什么?在main_screen() 内部或外部调用screen.mainloop()?正如我所说,如果在函数内部调用图像将显示图像,但如果在函数外部调用则不会显示。
  • 我尝试在函数 def login_success() 中调用 screen3.mainloop():
  • 对于第二种情况,最好不要调用screen3.mainloop(),因为已经有一个主循环(screen.mainloop())在运行。

标签: python image tkinter background


【解决方案1】:

应该很简单。当您在 tkinter 中处理图像时,您总是需要在您使用它的小部件上设置对该图像的引用。换句话说,做这样的事情:

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

特别是当您创建在函数范围或类似范围内保存图像的标签时,设置该引用非常重要,因为该标签实例的变量将在函数调用结束后消失。

PS:为了更清楚地了解主小部件和小的性能改进,在初始化小部件时总是给它一个主小部件。我知道 tkinter 也会自动将最后创建的 Tk 实例分配为 master 本身,但是 a) 是否需要不必要的计算能力 b) 是否更容易跟踪哪个小部件是另一个小部件的孩子等等。 ;)

【讨论】:

  • 我很抱歉,作为一个从互联网学习编码的完整初学者,你能否澄清一下你给小部件一个主小部件的意思?提前谢谢!
  • 添加这个,并在我的情况下将根更改为 screen3。成功了,谢谢!
  • 不用道歉,我们都已经开始了一次。但是要详细解释什么是主小部件,评论太长了,所以请阅读这篇文章和以下内容:effbot.org/tkinterbook/tkinter-whats-tkinter.htm 解释很好,从那里你可以继续描述其他小部件等等. ^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多