Deepak Jha
Deepak Jha

Reputation: 11

How to get cursor positions on click and drag event in python?

I want to get all the cursor positions till i left click and drag the mouse on the tkinter widget screen in python.

The below code just provides the left click position and not the positions on dragging the mouse after left click event.

import tkinter as tk

root = tk.Tk()

def leftClick(event):
    x, y = event.x, event.y
    print('({}, {}) -> LEFT'.format(x,y))

root.bind('<Button-1>',leftClick)

root.mainloop()

Is there any way to get positions of drag event

Upvotes: 0

Views: 1495

Answers (1)

Brett La Pierre
Brett La Pierre

Reputation: 533

I built a screen snipping program and here is one of the methods from it.

  def on_move_press(self, event):
        self.curX, self.curY = (event.x, event.y)
        # expand rectangle as you drag the mouse
        print(self.curX)
        print(self.curY)
        self.screenCanvas.coords(self.rect, self.start_x, self.start_y, self.curX, self.curY)

This will dynamically update when the user drags the snipping rectangle and print the values of the Current X and Current Y position (until the user releases).

This is activated by using the B1-Motion arguement as seen below.

self.screenCanvas.bind("<B1-Motion>", self.on_move_press)

Hopefully this helps!

Upvotes: 1

Related Questions