0

I have a set of code

photo = PhotoImage(file = "computer.png")
label = Label(root, image = photo)
label.pack()

When it is defined in the main program, it executes. When it is defined in a function as

def callback():
    photo = PhotoImage(file = "computer.png")
    label = Label(root, image = photo)
    label.pack()
    print ("click!")

then only click! was printed on python shell and nothing else. This code is to display an image on windows form developed using Tkinter

Call to the function was earlier made with menu command but there was no output than through a button with same result

This is inline code

root = Tk()
root.title('View')
root.geometry('600x400')
photo = PhotoImage(file = "computer.png")
label = Label(root, image = photo)
label.pack() 

This is the function

def callback():
    photo = PhotoImage(file = "computer.png")
    label = Label(root, image = photo)
    label.pack()
    print ("click!")

call through menu command

viewmenu.add_command(label="1:1 Zoom", command=About)

call through button click

b = Button(root, text="OK", command=callback)
b.pack()

The expected result is to display the image on Tkinter winform and the actual result is nothing just printing click! on python shell

Anant Mitra
  • 13
  • 1
  • 3

1 Answers1

0

Indeed, in the inline code, photo object persist in the memory. But when you call the function, since photo is a variable defined in the function scope, it's destroyed when function job finishes (its shown and destroyed so fast that you do not notice it). In the code below, when photo is defined as a global variable, you get the desired result:

from tkinter import *

def callback():
    global photo
    photo = PhotoImage(file = "computer.png")
    label = Label(root, image = photo)
    label.pack()
    print ("click!")

root = Tk()
b = Button(root, text="OK", command=callback)
b.pack()
root.mainloop()

Also you can define the photo as an attribute of the root object:

def callback():
    root.photo = PhotoImage(file = "2.png")
    label = Label(root, image = root.photo)
    label.pack()
    print ("click!")

Following an object oriented paradigm make organization of the code easier. Please read this answer for more information.

Masoud
  • 1,270
  • 7
  • 12