Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

Below is all of the code. But I can't understand about two lines of code in the function definitions, pLabel.configure(image = photo) and pLabel.image = photo. What's the meaning of these two lines? When I search it google, it says 'keep reference', but I can't fully understand 'keep reference'.

from tkinter import *

from time import *

fnameList = ["test1.gif", "test2.gif", "test3.gif", "test4.gif", "test5.gif",

"test6.gif", "test7.gif", "test8.gif", "test9.gif",]

photoList = [None] * 9

num = 0

def clickNext() :

    global num

    num += 1

    if num > 8 :

        num = 0

    photo = PhotoImage(file = "chapter10/gif/" + fnameList[num])

    pLabel.configure(image = photo)

    pLabel.image = photo

def clickPrev() :

    global num

    num -= 1

    if num < 0 :

        num = 8

    photo = PhotoImage(file = "chapter10/gif/" + fnameList[num])

    pLabel.configure(image = photo)

    pLabel.image = photo

window = Tk()

window.geometry("700x500")

window.title("album")

btnPrev = Button(window, text = "<< prev", command = clickPrev)

btnNext = Button(window, text = "next >>", command = clickNext)

window.bind("<Up>", clickNext)      # PageUp key click

window.bind("<Down>", clickPrev)    # PageDown key click

photo = PhotoImage(file = "chapter10/gif/" + fnameList[0])

pLabel = Label(window, image = photo)

btnPrev.place(x = 250, y = 10)

btnNext.place(x = 400, y = 10)

pLabel.place(x = 15, y = 50)

window.mainloop() 

1 Answer

0 votes
by (36.8k points)

The first line is configuring the Label widget to display the photo image object. The second line is storing a reference to this image object by explicitly adding it as an attribute named image to the Label widget. This is so the photo image object won't automatically be garbage collected when the function returns (because the photo is a local variable in both functions).

This is needed because the widget configure() the method doesn't do it (as one would expect because that's how things usually work in Python — but Tkinter is different).

Do check out Python for data science course which helps you understand from scratch 

Related questions

Browse Categories

...