不能将图像放置在tkinter Label对象中



我正在尝试插入一个图像到tkinter标签。

该图像不显示在标签对象中。在网上找不到明确的解决方案。'

下面是python文件的源代码:

import tkinter as tk
from PIL import Image, ImageTk

class LoginPage(tk.Tk):
def __init__(self, WindowName='Login', WindowWidth=960, WindowHeight=540, bgColor='#181A20'):
super().__init__()
self.title(WindowName)  # Setting the Window Name
self.configure(background=bgColor)  # Setting the Window BG Color
# Centering the Window According to Window Size#
scr_width = self.winfo_screenwidth()
scr_height = self.winfo_screenheight()
x = (scr_width/2) - (WindowWidth/2)
y = (scr_height/2)-(WindowHeight/2)
self.geometry('%dx%d+%d+%d' % (WindowWidth, WindowHeight, x, y))
# Setting the Window Icon
# Resizing the image
png = Image.open('./res/logo_no_text_yellow.png')
png = png.resize((50, 50))
# Placing the Window Icon
photo = ImageTk.PhotoImage(png)
self.wm_iconphoto(False, photo)
# Main Logo Label
self.label = tk.Label(self, background=bgColor)
png1 = Image.open('./res/logo yellow.png')
png1 = png1.resize((148, 148))
photo1 = ImageTk.PhotoImage(png1)
self.label.configure(image=photo1)
self.label.place(x=285, y=24)

test = LoginPage()
test.mainloop()

这是窗口的截图:

输入图片描述

您需要保存对图像的引用,否则Tkinter将无法找到它:

# Main Logo Label
self.label = tk.Label(self, background=bgColor)
png1 = Image.open('Canon.jpg')
png1 = png1.resize((148, 148))
photo1 = ImageTk.PhotoImage(png1)
self.label.configure(image=photo1)
self.label.image = photo1  # Save reference to image
self.label.place(x=285, y=24)

或者您可以将图像引用存储在对象中:

# Main Logo Label
self.label = tk.Label(self, background=bgColor)
png1 = Image.open('Canon.jpg')
png1 = png1.resize((148, 148))
self.photo1 = ImageTk.PhotoImage(png1)  # Storing as instance variable
self.label.configure(image=self.photo1)
self.label.place(x=285, y=24)

最新更新