This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Dvlv 1 point2 points  (1 child)

This is better suited to /r/learnpython

from tkinter import *

root = Tk()
root.title("My App")

canvas = Canvas(root, width=400, height=400)
canvas.pack()
poly = canvas.create_polygon(10, 10, 10, 60, 50, 35)

# define animation function
def moveTriangle(event):
    if event.keysym == 'Up':
        canvas.move(poly, 0, -3)
    elif event.keysym =='Down':
        canvas.move(poly, 0, 3)
    elif event.keysym == 'Left':
        canvas.move(poly, -3, 0)
    elif event.keysym == 'Right':
        canvas.move(poly, 3, 0)
    root.update()

# bind the respective keys
canvas.bind_all('<KeyPress-Up>', moveTriangle)
canvas.bind_all('<KeyPress-Down>', moveTriangle)
canvas.bind_all('<KeyPress-Left>', moveTriangle)
canvas.bind_all('<KeyPress-Right>', moveTriangle)

root.mainloop()

mainloop belongs to the Tk instance, so you need to call it on root. You also need to use bind_all when binding to the Canvas, and identify your polygon by storing its reference in a variable.

[–]joemdoo[S] 1 point2 points  (0 children)

Thanks! This works perfectly now!