1
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.

bbiot426
  • 37
  • 6
  • As the function says, `.configure(image=...)` is to configure the `image` option which defines the image to be shown. Whereas `.image` is an attribute (it can be any name) to save the reference of the image so that the image will not be garbage collected when the image is configured inside a function. `.image = ...` is not necessary if the image is configured in the global scope. – acw1668 Apr 26 '22 at 11:46
  • Then why `.configure( image = photo1 )` is valid, not `.configure( image = pLabel.image )` ? And the code `.image= ...` is written below `.configure()` so how `.configure()` get that? as i know, codes are processed in order of written... – bbiot426 Apr 26 '22 at 13:02
  • Read my comment carefully. – acw1668 Apr 26 '22 at 14:02

1 Answers1

1

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?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685