问题描述
我正在使用 Tkinter 制作 GUI 并驱动机器人.
I'm using Tkinter to make a GUI and drive a robot.
我有 4 个按钮:FORWARD
、RIGHT
、BACKWARD
和 LEFT
.我想让机器人在按下 Button 时移动,并在松开 Button 时停止.
I have 4 Buttons: FORWARD
, RIGHT
, BACKWARD
and LEFT
. I want to make the robot move as long as the Button is being pressed, and stop when the Button is released.
如何在 Tkinter 中识别按钮何时被释放?
How can I identify when a Button is released in Tkinter?
推荐答案
您可以独立地为 和
事件创建绑定.
You can create bindings for the <ButtonPress>
and <ButtonRelease>
events independently.
这里是学习事件和绑定的一个很好的起点:http:///effbot.org/tkinterbook/tkinter-events-and-bindings.htm
A good starting point for learning about events and bindings is here: 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() + "
")
self.text.see("end")
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
这篇关于如何识别 Button 在 Tkinter 中何时被释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!