I tried to make a image as background in a frame, the code is as follows,
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 image seems to take a place holder on the top frame, but no image is shown, I am wondering how to fix the issue.
if you take a look at 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.
so you simply need to keep a reference to the PhotoImage
for the code to work:
def initUI(self):
# create a background image
self.photo_bg = PhotoImage(file="building.gif")
building = self.make_label(self.parent, image=self.photo_bg)