单击按钮时的 Tkinter?
Tkinter when a button is clicked?
所以我在 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()
使用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()
所以我在 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()
使用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()