Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tkinter coords
#4
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()
Reply


Messages In This Thread
Tkinter coords - by dan789 - Dec-17-2018, 04:26 PM
RE: Tkinter coords - by wuf - Dec-17-2018, 06:04 PM
RE: Tkinter coords - by Larz60+ - Dec-17-2018, 06:55 PM
RE: Tkinter coords - by deanhystad - Aug-07-2023, 03:14 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020