Tkinter PhotoImage 背景图像未显示

Tkinter PhotoImage background image not showing

我试过在frame中做一个图片作为背景,代码如下,

from tkinter import * 

class LoginFrame(Frame):
    def __init__(self, parent):
        #Frame.__init__(self, parent)
        super(LoginFrame, self).__init__()

        self.parent = parent        
        self.initUI()

    # initialize the login screen UI  
    def initUI(self):
        # create a background image 
        photo_bg = PhotoImage(file="building.gif")          
        building = self.make_label(self.parent, image=photo_bg)       


    def make_label(self, parent, caption=NONE, side=TOP, **options):
        label = Label(parent, text=caption, **options)

        if side is not TOP:
            label.pack(side=side)
        else:
            label.pack()

        return label


def main():
    top = Tk()    
    app = LoginFrame(top)
    top.mainloop()


if __name__ == '__main__':
    main()

图像似乎在顶部框架上占了一个位置,但没有显示图像,我想知道如何解决这个问题。

如果你看一下 the Tkinter docs:

Tk will not keep a reference to the image. When the last Python reference to the image object is deleted, the image data is deleted as well, and Tk will display an empty box wherever the image was used.

因此您只需保留对 PhotoImage 的引用即可使代码正常工作:

def initUI(self):
    # create a background image 
    self.photo_bg = PhotoImage(file="building.gif")            
    building = self.make_label(self.parent, image=self.photo_bg)