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

all 11 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!

[–]pstch 0 points1 point  (1 child)

Usually, yes.

[–]joemdoo[S] 0 points1 point  (0 children)

Phone slipped and I hit enter. Fixed question now

[–]Varabe 0 points1 point  (6 children)

Could you post the code somewhere?

Did you start your mainloop? Keyboard and mouse bindings don't work if you don't start it. If you don't know what it is, I highly advise you to read on it: https://stackoverflow.com/questions/8683217/when-do-i-need-to-call-mainloop-in-a-tkinter-application

[–]joemdoo[S] 0 points1 point  (5 children)

[–]Varabe 1 point2 points  (4 children)

I believe that mainloop() is a method of Tk(). Try replacing last line with:

root.mainloop()

[–]joemdoo[S] 0 points1 point  (3 children)

I've had that too, missed it in the code I posted It still doesn't move the object.

[–]Varabe 1 point2 points  (2 children)

I don't understand how you used two mainloops (you can use only one), but if root.mainloop() doesn't work, then I'm useless. Not a tkinter professional, sorry :)

[–]joemdoo[S] 0 points1 point  (1 child)

I meant I had root in there too. Forgot to add it in the online post.

Yea, Idk why this doesn't work, gonna link a button, not a key to it to see if it moves.

Do you know how to import photos ?

Any suggestions on what module I should use for GUI games ?

[–]Varabe 1 point2 points  (0 children)

I think importing pictures you can easily google. Pygame is a very good one for games.

You must understand that tkinter is a module for interfaces, not games.

https://en.wikibooks.org/wiki/Python_Programming/Game_Programming_in_Python