Question

I seem to have a problem with the following code

import tkinter

window = tkinter.Tk()

window.geometry("1000x1000")

window.title(" Team Insanity login")

photo = tkinter.PhotoImage(file="content-large-white.gif")

def login():

    user = entuser.get()

    password = entpassword.get()

    if (user == "X-box") and (password == "d0ct0r"):
       photo = tkinter.PhotoImage(file="Trmn8atrmn8ter.gif")
       lblname.configure(text = "Welcome X-box!")

    elif (user == "Chloe") and (password == "l3ad3r"):
       photo = tkinter.PhotoImage(file="chloecat194.gif")
       lblname.configure(text = "Welcome Chloe!")

    lblpicture.configure(image=photo)

lblpicture = tkinter.Label(window, image=photo)

lblname = tkinter.Label(text="Please log in")

entuser = tkinter.Entry(window)

entpassword = tkinter.Entry(window)

btnlogin = tkinter.Button(text="Login", command=login)

lblname.pack()

lblpicture.pack(side=tkinter.LEFT)

entuser.pack()

entpassword.pack()

btnlogin.pack()



window.mainloop

You see, when attempting to run, it works fine. The login works as well, as it changes lblname's text. However, it does not seem to remember the changed picture, as it returns to a grey the same size as the picture requested.

it is also of note that, during debugging, i found that if a incorrectly spelled .update command made the picture stay up, but when corrected, made it flash the picture before reverting.

I'm not sure if it matters, but here are the pictures I am using

Trmn8atrmn8ter.gif = convert of http://chloecat194.deviantart.com/art/X-box-432590753?q=gallery%3AChloecat194%2F34413920&qo=16

Chloecat194.gif = convert of http://chloecat194.deviantart.com/art/Chloecat194-432590268?q=gallery%3AChloecat194%2F34413920&qo=18

Was it helpful?

Solution

In login, photo is a local variable. When the login function ends, the local variable photo may be garbage collected. Fredrik Lundh explains the problem this way:

When Python’s garbage collector discards the Tkinter object, Tkinter tells Tk to release the image. But since the image is in use by a widget, Tk doesn’t destroy it. Not completely. It just blanks the image, making it completely transparent…

The solution is to keep a reference to the PhotoImage. Since you aren't using classes, the easiest way to keep a reference is to make photo a global variable:

def login():
    global photo
    ...
    lblpicture.configure(image=photo)

This will also allow the content-large-white.gif to be the default image if neither the if-condition or the elif-condition is True; as it stands, Python raises a UnboundLocalError if it reaches that case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top