Aug-07-2023, 03:14 PM
(This post was last modified: Aug-07-2023, 03:14 PM by deanhystad.)
This is not correct:
self.canvas.move(self.field_icon_player, 10, 10)field_icon_player is the PhotoImage object, not a canvas image object. You need the id returned when you create the canvas image.
self.field_icon_player = self.canvas.create_image(j*50, i*50, anchor=NW, image=tkinter.PhotoImage(file="player.png")) ... for i in range(100): self.canvas.move(self.field_icon_player, 10, 10)This will move the image along the xy diagonal 1000 pixels. You will only see the image at the end of the move. The window will not get updated to show any of the between moves because you are blocking the mainloop. This can be seen in the example below:
import tkinter as tk from time import sleep root = tk.Tk() canvas = tk.Canvas(root, width=500, height=500) canvas.pack() dot = canvas.create_oval([0, 0, 20, 20], fill="red") root.update() for _ in range(10): canvas.move(dot, 10, 10) sleep(0.25) root.mainloop()One solution is update the canvas each time you move the image.
import tkinter as tk from time import sleep root = tk.Tk() canvas = tk.Canvas(root, width=500, height=500) canvas.pack() dot = canvas.create_oval([0, 0, 20, 20], fill="red") root.update() for _ in range(10): canvas.move(dot, 10, 10) canvas.update() sleep(0.25) root.mainloop()A better solution is to periodically call the move function.
import tkinter as tk def move_thing(thing, dx, dy, count, delay=250): canvas.move(thing, dx, dy) count = count - 1 if count > 0: canvas.after(delay, move_thing, thing, dx, dy, count, delay) root = tk.Tk() canvas = tk.Canvas(root, width=500, height=500) canvas.pack() dot = canvas.create_oval([0, 0, 20, 20], fill="red") move_thing(dot, 1, 1, 500, 10) root.mainloop()