0

I'm trying to get a .gif image to go into a canvas after being selected from my PC using filedialog.askopenfilename(). The canvas will take the image if I:

  1. Don't put it in a def and
  2. Do not use the filedialog, but I can't see why this would not work...
from tkinter import *
root=Tk()
root.geometry("600x600")
root.config(background="#FFFFFF")

canvas = Canvas(width=200,height=200)
canvas.grid(row=0,column=0)


def create_image():
    profileimage = filedialog.askopenfilename()
    i = PhotoImage(file=profileimage)
    canvas.create_image(0,0,image=i)

b = Button(text="Click", command=create_image).grid(row=1,column=0)
martineau
  • 119,623
  • 25
  • 170
  • 301
Victor Rodriguez
  • 531
  • 1
  • 10
  • 18

1 Answers1

1
global i       
def create_image(self): 
    global i
    profileimage = filedialog.askopenfilename()
    i = ImageTk.PhotoImage(Image.open(profileimage))
    canvas.create_image(0,0,image=i)   

Without referencing the image in a global variable, the image is stored in a local variable of the function that gets cleared by the garbage collector.