我正在用Tkinter做一个图形用户界面并驱动一个机器人。
我有4个按钮:FORWARD
,RIGHT
,BACKWARD
和LEFT
。我想让机器人在按钮被按下时移动,并在按钮被释放时停止。
如何在Tkinter中识别何时释放Button?
发布于 2013-05-14 17:53:40
您可以单独为<ButtonPress>
和<ButtonRelease>
事件创建绑定。
这里是学习事件和绑定的一个很好的起点: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()
https://stackoverflow.com/questions/16548757
复制相似问题