Simple key press event using python

Bydiwas

Simple key press event using python

we can create simple key press event using python by
binding the keys of the keyboard by using canvas.bind_all
function .
example: canvas.bind_all(‘<KeyPress-w>’,self.up)

Here is the simple example of key bind function:

from tkinter import *
import time
import random
win=Tk()
win.title("game")
canvas=Canvas(win,width=500,height=500)
canvas.pack()
t=("red","green","blue","grey","pink","black","yellow","orange")
class Bind():
       def __init__(self,color,size):
              self.canvas=canvas
              self.shape=canvas.create_oval(10,10,size,size,fill=color)
              self.x=random.randint(10,30)
             self.y=random.randint(-10,5)
             canvas.move(self.shape,250,250)
             self.canvas.bind_all('<KeyPress-d>', self.left)
             self.canvas.bind_all('<KeyPress-a> ', self.right)
             self.canvas.bind_all('<KeyPress-w> ', self.up)
             self.canvas.bind_all('<KeyPress-s> ', self.down)
       def draw(self):
       self.canvas.move(self.shape, self.x, self.y)
       po=canvas.coords(self.shape)
       if po[0]<=0 or po[2]>=500:
             self.x=-self.x
       if po[1]<=0 or po[3]>=500:
             self.y=-self.y
       def  left(self,evt):
              self.x=-10
       def  right(self,evt):
              self.x=10
       def up(self,evt):
             self.y=-10
       def down(self,evt):
             self.y=10
ball=Bind(random.choice(t),90)
while 1:
   ball.draw()
   win.update()
   time.sleep(0.05)

About the author

diwas administrator

Leave a Reply