python - 单击按钮时的 Tkinter?

标签 python tkinter tk-toolkit

所以我在 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 方法将按键与事件处理程序绑定(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 .

关于python - 单击按钮时的 Tkinter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33197971/

相关文章:

Python 旋转文件处理程序不旋转

python - 将数据保存在 Python 的调用库(pyinvoke)的上下文变量中

python - 使用 argsort 后如何取回订单?

python - 单击时从 URL 中删除获取参数

python - 再次点击按钮时出错

python - Tkinter 背景颜色问题

python - 如何摆脱 Python Tkinter 根窗口?

python - 何时在 tkinter 中使用包或网格布局?

python - Tkinter 列表框不显示函数结果

python - 退出 Tkinter 下拉菜单