Reputation: 3882
I'm trying to move a canvas circle across a tkinter window. I'nm using canvas.move, but it just has the object reappear in the new location. I want to actually see it travel. Is there a way to do this? I have the following:
def move_to(self, user_id, old_location, new_location):
self.user_list[user_id].set_location(new_location)
user_canvas_id = self.user_id_dict[user_id]
row_delta = new_location[ROW_INDEX] - old_location[ROW_INDEX]
col_delta = new_location[COL_INDEX] - old_location[COL_INDEX]
self.canvas.move(user_canvas_id, row_delta, col_delta)
def roaming_handler(self, user_id):
row = randrange(1, self.number_of_events * 125)
col = randrange(1, self.number_of_events * 125)
user_location = self.user_list[user_id].get_location()
self.move_to(user_id, user_location, (row, col))
There is also a variety of other things going on in the simulation at the time, and many of them will at one point or another call this.
Upvotes: 0
Views: 2030
Reputation: 1
I think you simply need to add a delay to the process, so you can "see it travel" as you said. This is how you do it:
canvas.update()
canvas.after(#number of miliseconds)
example code:
import tkinter
canvas = tkinter.Canvas(width=600, height=200)
canvas.pack()
canvas.create_oval(250, 50, 350, 100)
for x in range(100):
canvas.move(1, -5, 0)
canvas.update()
canvas.after(100)
Upvotes: 0
Reputation: 12180
I think this is what you are looking for:
You have to click on the circle and drag it to the new position
import tkinter
# Create some constants
RADIUS = 50
START_POS = 10
TAG = 'circle'
# The dragging function
def drag_circle(event, canvas):
r = RADIUS / 2
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
canvas.coords(TAG, x - r, y - r, x + r, y + r)
# Create window and canvas
root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.pack(fill=tkinter.BOTH, expand=True)
# Draw a circle
canvas.create_oval(
START_POS, START_POS, START_POS + RADIUS, START_POS + RADIUS,
fill='#555', width=0, tags=TAG)
# Bind function to event
canvas.tag_bind(TAG, '<B1-Motion>', lambda e: drag_circle(e, canvas))
# Run mainloop
root.mainloop()
Upvotes: 1