-1

I'm trying to display an Image in the canvas of tkinter window,the program runs perfectly but the image is not displaying in the canvas


import tkinter
from tkinter import *
from tkinter import ttk
import PIL
from PIL import Image,ImageTk

#-----------------------------------------------

root = Tk()
root.geometry("600x400")


toolbox = Frame(root,bg = "#494949",height = 50,width = 600,bd = 1,relief = RAISED)
toolbox.grid(row = 0,column = 0) 
toolbox.grid_propagate(0)

openf = Button(toolbox,text = "Show Image",bg = "gray",width = 30,relief = FLAT,command = lambda:showimg())
openf.grid(row = 0,column =0,sticky = "news")

cj = Canvas(root,width = 600,height = 300,relief = SUNKEN,bd = 1,bg = "#494949")
cj.grid(row = 1,column = 0,sticky = "news")

def showimg():
     g = ImageTk.PhotoImage(file = 'myphoto.png')
     t = cj.create_image(0,0,image = g,anchor = NW)

Divyesh Mehta
  • 191
  • 1
  • 9

1 Answers1

0

You don't need lambda or PIL, and you need to keep a reference to the image. Try this:

from tkinter import *
from tkinter import ttk

# functions come first in your code, then you don't need lambda to run them
def showimg():
     g = PhotoImage(file = 'myphoto.png')
     cj.img = g # keep a reference
     cj.create_image(0,0,image = g,anchor = NW)

root = Tk()
root.geometry("600x400")

toolbox = Frame(root,bg = "#494949",height = 50,width = 600,bd = 1,relief = RAISED)
toolbox.grid(row = 0,column = 0) 
toolbox.grid_propagate(0)

openf = Button(toolbox,text = "Show Image",bg = "gray",width = 30,relief = FLAT,command = showimg)
openf.grid(row = 0,column =0,sticky = "news")

cj = Canvas(root,width = 600,height = 300,relief = SUNKEN,bd = 1,bg = "#494949")
cj.grid(row = 1,column = 0,sticky = "news")
Novel
  • 13,406
  • 2
  • 25
  • 41