Tkinter coords - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: Tkinter coords (/thread-14785.html) |
Tkinter coords - dan789 - Dec-17-2018 Hi, I want to move my object (image) in tkinter, but it doesn´t work. This is what I have so far: class Playfield: ... def build_playfield(self): ... self.field_icon_player = tkinter.PhotoImage(file="player.png") ... self.canvas.create_image(j*50, i*50, anchor=NW, image=self.field_icon_player) ... for i in range(100): self.canvas.coords(self.field_icon_player, 10, 10)How can I move with this object? Coords doesn´t work in this case. Am I doing something wrong with implementing this inside a class? Thanks. RE: Tkinter coords - wuf - Dec-17-2018 Hi dan789 Try following: self.canvas.move(self.field_icon_player, 10, 10)wuf :-) RE: Tkinter coords - Larz60+ - Dec-17-2018 You can also move using coords, wuf's solution is better Quote: .coords(tagOrId, x0, y0, x1, y1, ..., xn, yn) RE: Tkinter coords - deanhystad - Aug-07-2023 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() |