基于python實現鼠標實時坐標監(jiān)測
更新時間:2023年11月23日 11:02:42 作者:就叫飛六吧
這篇文章主要給大家介紹了如何基于python實現鼠標實時坐標監(jiān)測,文章通過代碼示例介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下
python實現鼠標實時坐標監(jiān)測
一、說明
使用了以下技術和庫:
- tkinter:用于創(chuàng)建GUI界面。
- pyperclip:用于復制文本到剪貼板。
- pynput.mouse:用于監(jiān)聽鼠標事件,包括移動和點擊。
- threading:用于創(chuàng)建多線程,以便在后臺執(zhí)行鼠標事件監(jiān)聽和標簽更新的任務。
- time:用于控制線程休眠,以定時更新標簽文本。
二、代碼
# coding=gbk # 指定文件編碼為GBK
import tkinter as tk # 導入tkinter庫,用于創(chuàng)建GUI界面
import pyperclip # 導入pyperclip庫,用于復制文本到剪貼板
from pynput import mouse # 導入pynput庫的mouse模塊,用于監(jiān)聽鼠標事件
import threading # 導入threading庫,用于創(chuàng)建多線程
import time # 導入time庫,用于線程休眠
# 創(chuàng)建一個MouseCoordinateApp類,用于處理鼠標坐標顯示和復制
class MouseCoordinateApp:
def __init__(self):
self.root = tk.Tk() # 創(chuàng)建一個Tkinter窗口
self.root.title("鼠標坐標實時展示") # 設置窗口標題
self.root.geometry("350x80") # 設置窗口大小
self.root.resizable(False, False) # 禁止窗口大小調整
self.label = tk.Label(self.root, text="單機截取坐標:X: - , Y: -\n實時坐標:X: - , Y: -") # 創(chuàng)建一個標簽控件
self.label.pack() # 將標簽控件添加到窗口
copy_button = tk.Button(self.root, text="復制坐標", command=self.copy_coordinates) # 創(chuàng)建一個按鈕控件
copy_button.pack() # 將按鈕控件添加到窗口
self.root.attributes("-topmost", True) # 設置窗口置頂
self.extracted_coordinates = (0, 0) # 初始化截取坐標
self.current_coordinates = (0, 0) # 初始化實時坐標
self.last_extracted_coordinates = (0, 0) # 初始化上一次截取的坐標
self.update_interval = 0.1 # 更新標簽的時間間隔
threading.Thread(target=self.start_mouse_listener, daemon=True).start() # 創(chuàng)建并啟動鼠標事件監(jiān)聽的線程
threading.Thread(target=self.update_label_thread, daemon=True).start() # 創(chuàng)建并啟動標簽更新的線程
def copy_coordinates(self):
x, y = self.last_extracted_coordinates # 獲取上一次截取的坐標
coordinates = f"X: {x}, Y: {y}" # 格式化坐標文本
pyperclip.copy(coordinates) # 復制坐標文本到剪貼板
self.label.config(text=f"已復制坐標:{coordinates}") # 更新標簽文本
def start_mouse_listener(self):
with mouse.Listener(on_move=self.on_move, on_click=self.on_click) as listener:
listener.join() # 啟動鼠標事件監(jiān)聽
def on_move(self, x, y):
self.current_coordinates = (x, y) # 更新實時坐標
def on_click(self, x, y, button, pressed):
if pressed:
self.last_extracted_coordinates = self.extracted_coordinates # 更新上一次截取的坐標
self.extracted_coordinates = (x, y) # 如果鼠標被按下,更新截取坐標
def update_label_thread(self):
while True:
time.sleep(self.update_interval) # 線程休眠一段時間
self.update_label() # 更新標簽文本
def update_label(self):
extracted_x, extracted_y = self.extracted_coordinates # 獲取截取坐標
current_x, current_y = self.current_coordinates # 獲取實時坐標
self.label.config(text=f"截取坐標:X: {extracted_x}, Y: {extracted_y}\n實時坐標:X: {current_x}, Y: {current_y}")
def run(self):
self.root.mainloop() # 啟動主程序的主循環(huán)
if __name__ == "__main__":
app = MouseCoordinateApp() # 創(chuàng)建MouseCoordinateApp實例
app.run() # 啟動應用程序的主循環(huán)
三、效果

到此這篇關于基于python實現鼠標實時坐標監(jiān)測的文章就介紹到這了,更多相關python鼠標坐標監(jiān)測內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python 中 function(#) (X)格式 和 (#)在Python3.*中的注意事項
這篇文章主要介紹了Python 中 function(#) (X)格式 和 (#)在Python3.*中的注意事項,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11

