python - How can I identify when a Button is released in Tkinter? -
i'm using tkinter make gui , drive robot.
i have 4 buttons: forward
, right
, backward
, left
. want make robot move long button being pressed, , stop when button released.
how can identify when button released in tkinter?
you can create bindings <buttonpress>
, <buttonrelease>
events independently.
a starting point learning events , bindings here: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
here's working example:
import tkinter 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 pressed") def on_release(self, event): self.log("button released") def log(self, message): = time.strftime("%i:%m:%s", time.localtime()) self.text.insert("end", + " " + message.strip() + "\n") self.text.see("end") if __name__ == "__main__": root = tk.tk() example(root).pack(side="top", fill="both", expand=true) root.mainloop()
Comments
Post a Comment