python - 如何确定按钮何时在 Tkinter 中发布?

标签 python events button binding tkinter

我正在使用 Tkinter 制作 GUI 并驱动机器人。

我有 4 个按钮:FORWARDRIGHTBACKWARDLEFT。我想让机器人在按下按钮时一直移动,在释放按钮时停止。

在 Tkinter 中如何确定按钮何时被释放?

最佳答案

您可以为 <ButtonPress> 创建绑定(bind)和 <ButtonRelease>独立事件。

此处是了解事件和绑定(bind)的良好起点:http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

这是一个工作示例:

import Tkinter as tk
import time

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.button = tk.Button(self, text="Press me!")
        self.text = tk.Text(self, width=40, height=6)
        self.vsb = tk.Scrollbar(self, command=self.text.yview)
        self.text.configure(yscrollcommand=self.vsb.set)

        self.button.pack(side="top")
        self.vsb.pack(side="right", fill="y")
        self.text.pack(side="bottom", fill="x")

        self.button.bind("<ButtonPress>", self.on_press)
        self.button.bind("<ButtonRelease>", self.on_release)

    def on_press(self, event):
        self.log("button was pressed")

    def on_release(self, event):
        self.log("button was released")

    def log(self, message):
        now = time.strftime("%I:%M:%S", time.localtime())
        self.text.insert("end", now + " " + message.strip() + "\n")
        self.text.see("end")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

关于python - 如何确定按钮何时在 Tkinter 中发布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16548757/

相关文章:

python - 使用 iGraph 获取 python 中特定节点的邻居

javascript - 为什么一个元素在从 DOM 中移除后仍然可以访问?

C#如何将不同按钮的按钮文本设置到同一个文本框

python - 计算数据框中的 NaN 值

Python:遍历文件中的行

python - 在 Psycopg2 中高效地插入大量行

events - ext js 中是否有任何列单击事件?

c++ - Qt嵌入式Linux事件观察器

html - 将按钮放入 Canvas 中

html - 一行中的 Bootstrap 按钮