Why I need to use global statement inside function in tkinter?

Viewed 45

everyone, I want to use picture inside toplevel. But if I don't use global statement, I can't see my picture in toplevel which is the reason why I really confuse about. Does anyone know the reasons?

from tkinter import *
from PIL import ImageTk, Image

root = Tk()

def open():

    top = Toplevel()
    my_image = ImageTk.PhotoImage(Image.open(
    "C:\\Users\\86177\\Desktop\\python_source\\homo.jpeg"
                                        ))
    Label(top, image = my_image).pack()

Button(root, text = "open second window", command = open).pack()

root.mainloop()

In this code, when I click button to enter into toplevel, I can't see any image and picture in there. But when I add global statement inside function, I can see image inside toplevel.

from tkinter import *
from PIL import ImageTk, Image

root = Tk()

def open():
    global my_image
    top = Toplevel()
    my_image = ImageTk.PhotoImage(Image.open(
    "C:\\Users\\86177\\Desktop\\python_source\\homo.jpeg"
                                        ))
    Label(top, image = my_image).pack()

Button(root, text = "open second window", command = open).pack()

root.mainloop()

The location of file is right. In this code, I can see my image. Actually, I know global statement, but I don't think it is necessary to add global statement here because hole toplevel code is inside the open() function. Can someone explains the reason? Thank you so much.

1 Answers

But if I don't use global statement, I can't see my picture in toplevel ... . Does anyone know the reasons?

Python has something called a garbage collector. It watches objects and references to objects, and when it notices that an object no longer has variables that point to it, the garbage collector will free up the memory used by that object. This frees us from the tedious task of having to manage memory usage.

Inside a function, when you don't mark the image variable as global then it is considered a local variable. That means that when the function returns, python will free up the memory used by all variables in the function. If that variable points to an image, python will free up the memory used by the image because it thinks it isn't being used anymore since there are no longer any references to it.

By saving the reference to the image in a global variable (or in an instance variable), python sees that there is a persistent reference to the image and thus it needs to stay in memory.

Related