Reputation: 591
I have a simple canvas being created in a function, and i would like an image displayed on the canvas.
def start(root):
startframe = tkinter.Frame(root)
canvas = tkinter.Canvas(startframe,width=1280,height=720)
startframe.pack()
canvas.pack()
one = tkinter.PhotoImage('images\one.gif')
canvas.create_image((0,0),image=one,anchor='nw')
when i run the code i get a blank 1280x720 window, no image.
i have looked at the following website: http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm but i do not understand how to apply their example to my situation (i dont know what to create a reference to or how to create a reference, if that is my problem). I have also looked at some stack overflow questions but they did not help either.
Upvotes: 22
Views: 29137
Reputation: 144
I had the situation when image didn`t show up, when I call it in function, but otherwise everything was okay. That is my function
def ask_for_file():
f_types = [('PNG Images', '*.png')]
filename = askopenfilename(filetypes=f_types)
img = ImageTk.PhotoImage(file=filename)
canvas.config(height=img.height(), width=img.width())
canvas.create_image(0, 0, anchor=NW, image=img)
My solution was to add img = None
as global variable and change it inside function. It worked
img = None
def ask_for_file():
global img
f_types = [('PNG Images', '*.png')]
filename = askopenfilename(filetypes=f_types)
img = ImageTk.PhotoImage(file=filename)
canvas.config(height=img.height(), width=img.width())
canvas.create_image(0, 0, anchor=NW, image=img)
Upvotes: 2
Reputation: 11
How about canvas.update()
? I was suffering a similar problem. I am using grid, so instead of .pack
I needed to use .update
.
Upvotes: 1
Reputation: 369074
Escape backslashes in path string correctly. (or use r'raw string literal'
).
Prevent PhotoImage object being garbage collected.
specify the filename using file=...
option.
def start(root):
startframe = tkinter.Frame(root)
canvas = tkinter.Canvas(startframe,width=1280,height=720)
startframe.pack()
canvas.pack()
# Escape / raw string literal
one = tkinter.PhotoImage(file=r'images\one.gif')
root.one = one # to prevent the image garbage collected.
canvas.create_image((0,0), image=one, anchor='nw')
UPDATE
The two statements one = ...
and root.one = one
can be merged into one statement:
root.one = one = tkinter.PhotoImage(r'images\one.gif')
Upvotes: 45