How do I make the square move when pressing the "d" button (for example) on the keyboard?
from tkinter import *
root = Tk()
root.title('Snake')
root["width"] = 400
root["height"] = 400
field = Canvas(root)
x = 0
y = 0
def snake(x, y):
field.create_rectangle(10, 20, 30, 40)
field.grid(row=x, column=y)
x += 1
y += 1
return(x, y)
root.bind("<KeyPress>", snake(x=x, y=y))
root.mainloop()
An easy way is to use event.char. It returns the character of the button pressed. Then check which button it was and move it if it is w,a,s,d -
from tkinter import *
root = Tk()
root.title('Snake')
root["width"] = 400
root["height"] = 400
field = Canvas(root)
rect = field.create_rectangle(10, 20, 30, 40)
field.grid(row=0, column=0)
def snake(event):
x = 0 # Default
y = 0
if event.char == 'w':
y = -10
if event.char == 'a':
x = -10
if event.char == 's':
y = 10
if event.char == 'd':
x = 10
field.move(rect,x,y)
root.bind("<Key>", snake)
root.mainloop()
This is one way you can do it:
import tkinter as tk
from tkinter import Canvas
root = tk.Tk()
root.title('Snake')
root.geometry("450x450")
w = 400
h = 400
x = w//2
y = h//2
field = Canvas(root, width=w, heigh=h, bg="white")
field.pack(pady=5)
my_rectangle = field.create_rectangle(10, 20, 30, 40)
def left(event):
x = -10
y = 0
field.move(my_rectangle, x, y)
def right(event):
x = 10
y = 0
field.move(my_rectangle, x, y)
def up(event):
x = 0
y = -10
field.move(my_rectangle, x, y)
def down(event):
x = 0
y = 10
field.move(my_rectangle, x, y)
root.bind("<Left>", left)
root.bind("<Right>", right)
root.bind("<Up>", up)
root.bind("<Down>", down)
root.mainloop()
First create root, and give geometry to it, in this case it is 450x450.
After that create variables that will store height and width, and coordinates x and y. Then, create canvas (field) and in canvas specify where canvas will be located and geometry of canvas (and background color). When canvas is created, we create rectangle. Functions left, right, up and down will cover movement of rectangle on canvas. field.move(my_rectangle, x, y) - this line of code will move my_rectangle on canvas by x and y, or by left, right up or down, depends what is passed. root.bind("<Left>", left) - bind left arrow key to left function. Thats why event is parameter of fucntion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With