2015-10-18 162 views
2

所以即時在Tkinter做一個遊戲,但我想要做的是當我點擊我的鍵盤上的按鈕,例如「w」它運行一個函數,例如增加x 5。單擊按鈕時Tkinter?

繼承人我的代碼。

__author__ = 'Zac' 
from Tkinter import * 
from random import randint 

class Application: 
    def circle(self, r, x, y): 
     return (x-r, y-r, x+r, y+r) 

    def square(self, s, x, y): 
     return (x, y, s, s) 

    def __init__(self, canvas, r, x, y): 
     self.canvas = canvas 
     self.r = r 
     self.x = x 
     self.y = y 
     self.ball = canvas.create_oval(self.circle(r, x, y)) 


root = Tk() 
canvas = Canvas(root, width = 1000, height = 1000) 
canvas.pack() 

ball1 = Application(canvas, 20, 50, 50) 


root.mainloop() 

回答

4

使用widget.bind方法來綁定按鍵和事件處理程序。

例如:

.... 

ball1 = Application(canvas, 20, 50, 50) 

def increase_circle(event): 
    canvas.delete(ball1.ball) 
    ball1.r += 5 
    ball1.ball = canvas.create_oval(ball1.circle(ball1.r, ball1.x, ball1.y)) 

root.bind('<w>', increase_circle) # <--- Bind w-key-press with increase_circle 

root.mainloop() 

參見Events and Bindings

+0

謝謝你只有一個問題,你爲什麼事件? – Zac

+0

@Zac,我添加了一個鏈接。讀它會回答你的問題。 :) – falsetru