Paulo Schreiner
Paulo Schreiner

Reputation: 129

How to move objects diagonally in Tkinter's Canvas?

How can I make an object move diagonally in a Tkinter canvas every time someone presses two arrow keys at the same time? I'm creating a simple animation but it only moves up, down, left or right. Here's the code I have:

from tkinter import *
import time
root = Tk()
canvas = Canvas(root, width=800, height=800)
square = canvas.create_rectangle(0,0,50,50,outline='red')


def right(event):
 for i in range(5):
  canvas.move(ball,1,0)
  canvas.update()

def left(event):
 for i in range(5):
  canvas.move(ball,-1,0)
  canvas.update()

def down(event):
 for i in range(5):
  canvas.move(ball,0,1)
  canvas.update()

def up(event):
 for i in range(5):
  canvas.move(ball,0,-1)
  canvas.update()

root.bind('<Right>', right)
root.bind('<Left>', left)
root.bind('<Down>', down)
root.bind('<Up>', up)

canvas.pack()
root.mainloop()

Upvotes: 0

Views: 817

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36702

Keypresses in tkinter are individual events; to the exception of key modifiers (shift, control, alt), you cannot bind an action to the "simultaneous" pressing of two keys.

What you can do, is assign NE, SE, NW, SW moves to different keys.

I assigned the control of the movements to the following keys:

Q W E
A   D
Z X C 

other changes:

  • It is best practice to avoid star imports.
  • It was not necessary to update the canvas each time; move already redraws the changes on the canvas.
  • I assigned a 'speed' to the object, removed the repeated calling of movein a loop, and use the speed to determine the distance to move.
  • I renamed square to ball, so ball is defined.

the code:

import tkinter as tk


root = tk.Tk()
canvas = tk.Canvas(root, width=800, height=800)
ball = canvas.create_rectangle(0, 0, 50, 50, outline='red')

speed = 5

def w(event):
    canvas.move(ball, speed, 0)

def e(event):
    canvas.move(ball, -speed, 0)

def s(event):
    canvas.move(ball, 0, speed)

def n(event):
    canvas.move(ball, 0, -speed)

def nw(e):
    canvas.move(ball, speed, -speed)

def sw(e):
    canvas.move(ball, speed, speed)

def ne(e):
    canvas.move(ball, -speed, -speed)

def se(e):
    canvas.move(ball, -speed, speed)

root.bind('<KeyPress-w>', n)
root.bind('<KeyPress-e>', nw)
root.bind('<KeyPress-d>', w)
root.bind('<KeyPress-c>', sw)
root.bind('<KeyPress-x>', s)
root.bind('<KeyPress-z>', se)
root.bind('<KeyPress-a>', e)
root.bind('<KeyPress-q>', ne)

canvas.pack()
root.mainloop()

Upvotes: 1

Related Questions