Home > other >  What is difference between label.configure(image=value) and label.image=value?
What is difference between label.configure(image=value) and label.image=value?

Time:04-27

from tkinter import *
from tkinter.filedialog import *

wd = Tk()

def func_open():
    fname = askopenfilename(parent=wd, filetypes=( ("gifs","*.gif"), ("alls","*.*") ))
    photo1 = PhotoImage( file = fname )
    pLabel.configure( image = photo1 )
    pLabel.image=photo1

temp = PhotoImage()
pLabel = Label(wd, image = temp )
pLabel.pack(expand=1)

mainMenu = Menu(wd)
wd.config(menu=mainMenu)
fileMenu = Menu(mainMenu)
mainMenu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="Open",command=func_open)

wd.mainloop()

2 lines of code above,
pLabel.configure( image = photo1 )
pLabel.image=photo1
if i remove one of these, func_open() can't print image file.
To me, it seems like both line says same thing,
as pLabel.configure( image = photo1 ) put image through argument photo1
and pLabel.image=photo1 is directly put photo1 to pLabel's image.
I tried search that .configure() method but i couldn't get any understandable imformation.

CodePudding user response:

Widgets have internal configuration options that control its appearance and behavior. When you call the configure method, you are giving one of those options a value. Thus, pLabel.configure( image = photo1 ) sets the image option to the value of the photo1 variable.

When you do pLabel.image=photo1, you are creating a new instance variable on the pLabel python object named image and setting it to the value of the photo1 variable. The underlying tkinter widget has no knowledge of this attribute, and isn't affected by this attribute.

This is a common idiom for saving a reference to the image. The use of the word image is completely arbitrary, using pLabel.xyzzy=photo1 or pLabel.save_this=photo1 would solve the exact same problem.

For more information see Why does Tkinter image not show up if created in a function?

  • Related