-1

I am busy making a game in python using tkinter, time and PIL, and I have a character that I want to animate very simply, but when I try this code, it doesn't do anything then jumps to the last image, can someone please tell me why this is?

def move_char(event):
if event.keysym == "w":
    character = ch1
    c.delete(character)
    character = ch2_1
    c.create_image(725, 450, image = character)
    sleep(0.2)
    c.delete(character)
    character = ch2
    c.create_image(725, 450, image = character)
    sleep(0.2)
    c.delete(character)
    character = ch2_2
    c.create_image(725, 450, image = character)
    sleep(0.2)
    c.delete(character)
    character = ch2
    c.create_image(725, 450, image = character)

Appreciate any help

  • Reading [Tkinter understanding mainloop](https://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop) will be help. – jizhihaoSAMA Apr 09 '20 at 07:57
  • Does this answer your question? [tkinter and time.sleep](https://stackoverflow.com/questions/10393886/tkinter-and-time-sleep) – stovfl Apr 09 '20 at 08:00
  • I'm afraid that if I use the examples in Tkinter understanding mainloop, my program crashes, and PhotoImage (class of character) has no after method, so if I use c.after(), it has the same problem – Captainvon123 Apr 09 '20 at 08:45
  • Base on your code, `c` is a `Canvas`, and `ch1`, `ch2`, `ch2_1` and `ch2_2` are instances of `PhotoImage` or `PIL.ImageTk.PhotoImage`. So `c.delete(character)` will not delete the image in the canvas. In order to see the effect, you need to add `c.update()` after each `c.create_image(...)`. – acw1668 Apr 09 '20 at 09:07

1 Answers1

0

Since character is a reference to PhotoImage, c.delete(character) will not delete the image in the canvas as you wish. You can use tag option of c.create_image(...) to identify the image and use the tag in c.delete(). Also in order to see the animation effect, you need to call c.update() after c.create_image(...).

Below is an updated move_char(...):

def move_char(event):
    if event.keysym == "w":
        # loop through the images
        for ch in (ch2_1, ch2, ch2_2, ch2):
            c.delete('char-image') # remove current image
            c.create_image(725, 450, image=ch, tag='char-image') # use tag to identify image
            c.update() # make the change effective
            sleep(0.2)
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • Thank you, the only problem I still have is that the original picture is always showing in the background, but i'm guessing this is to do with the way I have placed him. :) – Captainvon123 Apr 14 '20 at 10:09
  • Do you mean image `ch1`? Just create the image with `tag='char-image'` as well. – acw1668 Apr 14 '20 at 10:19
  • Thank you, I did try this but I did an oopsie and used an underscore instead of a dash, but that is now fixed haha, appreciate your help :) – Captainvon123 Apr 14 '20 at 10:27