单击按钮时Tkinter?

问题描述:

所以即时在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() 

使用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