We go in parts:
-
First of all you are specifying the event badly, the name of the event must be between angle brackets:
'<Up>'
You can see the correct syntax in the Tkinter documentation .
-
To the function movertriangulo
you define it like this: def movertriangulo(evento)
but inside it you use the parameter event
no evento
, you must correct this.
-
This is not an error in itself but if a very bad practice , you import the module in the form:
from tkinter import *
This is dangerous and should never be done. You can find unpleasant surprises and difficult to find bugs, especially with extensive codes and complex libraries. Use some of these formulas instead:
import tkinter
from tkinter import Tk, Camvas
import tkinter as tk
-
You do not start the mainloop of your application, if you use the IDLE it runs correctly because the IDLE itself uses Tkinter, so it has its own mainloop. If you launch it from the console or from another side that is not the IDLE, the application will not start.
The code would look like this:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.create_polygon(10,10,10,60,50,35)
def movertriangulo(event):
if event.keysym == 'Up':
canvas.move(1,0,-3)
elif event.keysym == 'Down':
canvas.move(1,0,3)
elif event.keysym == 'Left':
canvas.move(1,-3,0)
elif event.keysym == 'Right':
canvas.move(1,3,0)
canvas.bind_all('<Up>',movertriangulo)
canvas.bind_all('<Down>',movertriangulo)
canvas.bind_all('<Left>',movertriangulo)
canvas.bind_all('<Right>',movertriangulo)
root.mainloop()
Another option is to implement a function for each event:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()
canvas.create_polygon(10,10,10,60,50,35)
def izquierda(event):
canvas.move(1,-3,0)
def derecha(event):
canvas.move(1,3,0)
def abajo(event):
canvas.move(1,0,3)
def arriba(event):
canvas.move(1,0,-3)
canvas.bind_all('<Up>',arriba)
canvas.bind_all('<Down>',abajo)
canvas.bind_all('<Left>',izquierda)
canvas.bind_all('<Right>',derecha)
root.mainloop()