How Python Monitors Mouse Operations and Checks the Path of Selected Files

Asked 2 years ago, Updated 2 years ago, 276 views

"I would like to do the process of ""importing dragged and dropped files into the software""

"

Monitor mouse activity on Windows or Mac in Python
·Detects that a file has been clicked on a desktop
·Retrieve file path
·Detected that the mouse was released

Is there a way to write something like this?

python

2022-09-30 22:02

1 Answers

Instead of monitoring mouse operations, you can handle files that have been dragged and dropped by the mouse into Python's GUI application without opening a file dialog.
This requires an external package, such as TkDND.(Refer to Pre-installation)

Reference: [Python] tkinter: Drag and drop files (path retrieval, image display)

Preparation

 pip install tkinterdnd2

sample code

import tkinter ask
from tkinter import ttk
from tkinterdnd2 import TkinterDnDastdnd
from tkinterdnd2 import DND_FILES

# drop event
def drop(event:tdnd.DnDEvent):
    label=event.widget
    label.configure(text=event.data)
    print(label.labelText)

w=tdnd.Tk()
label=ttk.Label(w,text="Drop the file here to see the path\n")
label.pack (fill=tk.BOTH, expand=True)
label.grid (row=0, column=0)

# adapt labels to drag-and-drop files
label.drop_target_register(DND_FILES)
label.dnd_bind('<<Drop>>', drop)

w.mainloop()

The following are Snake Feet for PC-savvy people.

Implementations that detect which files have been clicked or dropped on the desktop or explorer are not very realistic.
External packages, such as pynput, can monitor mouse behavior, but retrieving file paths from click location information is very difficult.

If an implementation that detects dragging and dropping or copying to a specific folder instead of a screen can replace it, you can also deploy the Watchdog package for folder monitoring.

D&D is unexpectedly expensive to operate, so it may be practical to place the Python program in the Send menu on the right-click menu and handle the full path received in the arguments.
"However, in the standard Windows 11 context menu, the ""send"" menu is hidden (unconfirmed) and it's hard to use after all..."


2022-09-30 22:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.