Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I bind an event to the left mouse button being held down?

I need a command to be executed as long as the left mouse button is being held down.

like image 564
rectangletangle Avatar asked Jul 20 '10 07:07

rectangletangle


1 Answers

If you want "something to happen" without any intervening events (ie: without the user moving the mouse or pressing any other buttons) your only choice is to poll. Set a flag when the button is pressed, unset it when released. While polling, check the flag and run your code if its set.

Here's something to illustrate the point:

import Tkinter

class App:
    def __init__(self, root):
        self.root = root
        self.mouse_pressed = False
        f = Tkinter.Frame(width=100, height=100, background="bisque")
        f.pack(padx=100, pady=100)
        f.bind("<ButtonPress-1>", self.OnMouseDown)
        f.bind("<ButtonRelease-1>", self.OnMouseUp)

    def do_work(self):
        x = self.root.winfo_pointerx()
        y = self.root.winfo_pointery()
        print "button is being pressed... %s/%s" % (x, y)

    def OnMouseDown(self, event):
        self.mouse_pressed = True
        self.poll()

    def OnMouseUp(self, event):
        self.root.after_cancel(self.after_id)

    def poll(self):
        if self.mouse_pressed:
            self.do_work()
            self.after_id = self.root.after(250, self.poll)

root=Tkinter.Tk()
app = App(root)
root.mainloop()

However, polling is generally not necessary in a GUI app. You probably only care about what happens while the mouse is pressed and is moving. In that case, instead of the poll function simply bind do_work to a <B1-Motion> event.

like image 188
Bryan Oakley Avatar answered Oct 14 '22 08:10

Bryan Oakley