Tkinter Canvas Message Bindings
The main idea is that the system can be used to receive messages from the keyboard and react to them. For example, when it happens to press the right shift key, you can control the ball to move to the right, for example, we can design the function as follows.
def ballMove(event):
canvas.move(1, 5, 0) # Assuming a shift of 5 pixels
The program design function for moving the ball by pressing the right shift key can be designed as follows.
def ballMove(event):
if event.keysym == 'Right':
canvas.move(1, 5, 0)
For the main application, you need to use the canvas.bind_all() function to perform the message binding work, which is written as follows.
canvas.bind_all('<KeyPress-Left>', ballMove) # Left shift key
canvas.bind_all('<KeyPress-Right>', ballMove) # Right shift key
canvas.bind_all('<KeyPress-Up>', ballMove) # Up shift key
canvas.bind_all('<KeyPress-Down>', ballMove) # Down shift key
The above function mainly tells the program what the message received from the keyboard is, and then calls the ballMove() function to perform the work of the keyboard message.
Example#1
When the program starts executing, there is a red ball in the center of the canvas. You can move the ball right, left, up, or down by pressing the right, left, up, or down keys on the keyboard, 5 pixels at a time.
from tkinter import *
import time
def ballMove(event):
if event.keysym == 'Left': # Left shift ################################
canvas.move(1, -5, 0)
if event.keysym == 'Right': # Right shift
canvas.move(1, 5, 0)
if event.keysym == 'Up': # Up shift
canvas.move(1, 0, -5)
if event.keysym == 'Down': # Down shift
canvas.move(1, 0, 5)
tk = Tk()
tk.title("apidemos.com")
canvas = Canvas(tk,width=500, height=300) # Create Canvas
canvas.pack()
canvas.create_oval(225,125,275,175,fill="red")
canvas.bind_all('<KeyPress-Left>',ballMove)
canvas.bind_all('<KeyPress-Right>',ballMove)
canvas.bind_all('<KeyPress-Up>',ballMove)
canvas.bind_all('<KeyPress-Down>',ballMove)
mainloop()
# tk.mainloop()
Output: