所以我在Tkinter制作游戏,但我想要做的是当我点击键盘上的一个按钮时,例如“w”,它会运行一个函数,例如将x增加5。
继承我的代码。
__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()
答案 0 :(得分:4)
使用widget.bind
方法将keypress与事件处理程序绑定。
例如:
....
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()