Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

python - How can I identify when a Button is released in Tkinter?

I'm using Tkinter to make a GUI and drive a robot.

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.

How can I identify when a Button is released in Tkinter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create bindings for the <ButtonPress> and <ButtonRelease> events independently.

A good starting point for learning about events and bindings is here: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

Here's a working example:

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...