How to associate an event with the left mouse button pressed?

I need a command to execute if the left mouse button is held down.

+4
source share
3 answers

See table 7-1 of the documents. There are events that indicate movement when a button is pressed, <B1-Motion> , <B2-Motion> , etc.

If you are not talking about the “press and movement” event, you can start doing your business on <Button-1> and stop doing this when you receive <B1-Release> .

+4
source

If you want “something happened” without any intermediate events (that is, without the user moving the mouse or pressing any other buttons), your only choice is to poll. Set the flag when the button is pressed, cancel it when released. During the survey, check the flag and run your code, if installed.

Here is something to illustrate:

 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 usually not required in a GUI application. You probably only care about what happens when the mouse is pressed and moves. In this case, instead of polling, just bind do_work to the <B1-Motion> event.

+5
source

Use mouse move / move events and check modifier flags. Mouse buttons will appear there.

+1
source

Source: https://habr.com/ru/post/1316251/


All Articles