Mr Bozkurt
Mr Bozkurt

Reputation: 47

How can I change the picture inside Tkinter?

from tkinter import  *
import threading
view=Tk()
canvas=Canvas(view,width=800, height=800)
canvas.pack()
myImage=PhotoImage(file='a.png')
canvas.create_image(0,0,anchor=NW,image=myImage)
def changeImg():
    print("ı came")
    canvas.delete("all")
    myImage = PhotoImage(file='add.png')
    canvas.itemconfigure(view,image=myImage)
    view.update()
timer=threading.Timer(5.0, changeImg)
timer.start()
view.mainloop()

It doesn't change the image. Just a white screen after 5 secs later.

Upvotes: 0

Views: 96

Answers (1)

figbeam
figbeam

Reputation: 7176

As you delete the canvas image in function changeImg() it's useless to try to configure the canvas image.

canvas.delete("all")

A solution would be to create a new PhotoImage and assign it to a new canvas image.

Then, as always, you have to save a reference to the image or Tkinter will forget it when the function ends.

from tkinter import  *
import threading

view=Tk()
canvas=Canvas(view,width=800, height=800)
canvas.pack()
myImage=PhotoImage(file='a.png')
canvas.create_image(0,0,anchor=NW,image=myImage)

def changeImg():
    print("ı came")
    canvas.delete("all")
    myImage = PhotoImage(file='add.png')    # Create new
    canvas.create_image(0,0,anchor=NW,image=myImage) # Create new
    canvas.image = myImage  # Save reference to new image
    view.update()

timer=threading.Timer(2.0, changeImg)
timer.start()
view.mainloop()

Upvotes: 1

Related Questions