簡體   English   中英

我怎樣才能不斷地將我的鼠標 position 放在 Tkinter window 和 ZA7F5F35426B9274171FC9231B58Z 之外?

[英]How can i constantly get my mouse position outside of Tkinter window with Python?

有沒有辦法不斷得到我的鼠標 position 並用 Python 打印它? 我知道使用 Tkinter 您可以通過將鼠標運動與類似的東西綁定來實現這一點,但我想要在 Tkinter 創建的 windows 之外也可以使用的東西

def motion(event):
    posx, posy = pyautogui.position()
    print("PosX = " + str(posx) + " PosY = " + str(posy))
root.bind('<Motion>', motion)

編輯:感謝您的回答,但我的問題不是很清楚,我需要一種在后台工作的方式,同時我可以在我的代碼上使用其他方法。 如果我使用while True我將被鎖定在此方法中。 例如,我需要與root.bind('<Motion>', motion)完全相同的東西,但它可以在根 window 之外工作。

您可以使用after()winfo_pointerxy()不斷獲取鼠標 position:

import tkinter as tk

root = tk.Tk()

lbl = tk.Label(root, width=20)
lbl.pack()

def get_mouse_pos():
    lbl.config(text='{}, {}'.format(*root.winfo_pointerxy()))
    root.after(100, get_mouse_pos)

get_mouse_pos()
root.mainloop()

您可以通過非常簡單的方式做到這一點。 您將需要 pyautogui

import pyautogui

while True:
    print(pyautogui.position())

Output:

Point(x=708, y=380)

試試這個可能對你有幫助

#!/usr/bin/python

import struct
import binhex

# You'll need to find the name of your particular mouse to put in here...
file = open("/dev/input/by-id/usb-Logitech_USB_Trackball-event-mouse","rb")


while True:
     byte = file.read(16)
#    h = ":".join("{:02x}".format(ord(c)) for c in byte)
#    print "byte=",h

    (type,code,value) =  struct.unpack_from('hhi', byte, offset=8)

    if type == 1 and value == 1:
        if code == 272:
            print ("LEFT PRESS")
        if code == 273:
            print("RIGHT PRESS")

    if type == 2:
        if code == 0:
            print("MOVE L/R",value)
        if code == 1:
            print("MOVE U/D",value)

通過使用pyxhook庫(用於 Linux 的pyhook實現)來管理它。 通過使用此解決方案,您將不會遇到被鎖定在while True循環中的缺點。 要停止捕獲,只需按“Esc”(event.Ascii == 27)。

import pyxhook
import pyautogui

def mouse_event(event):
    posx, posy = pyautogui.position()
    print ("PosX: " + str(posx) + ", PosY: " + str(posy))

def cancel_hookmanager(event):
    if event.Ascii == 27:
        hookman.cancel()

hookman = pyxhook.HookManager()
hookman.MouseMovement = mouse_event
hookman.KeyUp = cancel_hookmanager
hookman.HookKeyboard
hookman.HookMouse
hookman.start()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM