zack cook
zack cook

Reputation: 23

Keyboard control with tkinter

I am designing a simple game in python for a class I take in school. We have to use the tkinter package for our graphics and i'm running into trouble with getting wasd to control objects on a canvas. Everything I read online just confuses me more and more. Would it be possible to get a simple run down of how to do it or even a basic code example? I wanted to include code but I really currently have nothing to work with. All I am looking to do is w=up a=left s=down d=right to move a square around the screen(canvas). Thank you

Upvotes: 0

Views: 1656

Answers (1)

scotty3785
scotty3785

Reputation: 7006

Here is an example cut down from something I made a while back. Far from perfect but it show the basic principles.

from tkinter import *

class Ball:
    def __init__(self,canvas,**kw):
        self.canvas = canvas
        self.radius = kw.get('radius',20)
        self.pos_x = kw.get('pos_x',0)
        self.pos_y = kw.get('pos_y',0)
        self.color = kw.get('color','blue')
        self.create()
    def calculate_ball_pos(self):
        x1 = self.pos_x
        x2 = self.pos_x + self.radius
        y1 = self.pos_y
        y2 = self.pos_y + self.radius
        return x1,y1,x2,y2
    def create(self):
        coords = self.calculate_ball_pos()
        self.ball = self.canvas.create_oval(coords[0],coords[1],coords[2],coords[3])
        self.canvas.itemconfig(self.ball, fill=self.color)
    def move(self,x=0,y=0):
        self.pos_x += x
        self.pos_y += y        
        coords = self.calculate_ball_pos()
        self.canvas.coords(self.ball,coords[0],coords[1],coords[2],coords[3])

def keypress(event):
    """Recieve a keypress and move the ball by a specified amount"""
    print(event)
    if event.char == 'w':
        ball.move(0,-5)
    elif event.char == 's':
        ball.move(0,5)
    elif event.char == 'a':
        ball.move(-5,0)
    elif event.char == 'd':
        ball.move(5,0)
    else:
        pass


root = Tk()
mainCanvas = Canvas(root, width=200, height=200)
root.bind('w',keypress)
root.bind('s',keypress)
root.bind('a',keypress)
root.bind('d',keypress)
mainCanvas.grid()
ball = Ball(mainCanvas,pos_x=50,pos_y=50)

root.mainloop()

The ball will move up, down left or right with the w,s,a and d key respectively. Note that rather than redrawing the ball each time, I just move the object (change it's coordinates)

Should be pretty simple to make this work with a box instead. create_rectangle rather than create_oval

Upvotes: 1

Related Questions