python: 用threading实现获取屏幕鼠标位置用于拖动wxpython的窗口

网上查到然后自己写的,鼠标无论移动多快窗口都可以跟得上,有什么问题留言,谢谢

#!/usr/bin/env python
# -*-coding:utf-8 -*-

import threading
import win32api as api
import wx


class WorkerThread(threading.Thread):
    def __init__(self, frame):
        threading.Thread.__init__(self)
        self.frame = frame
        self.timeToQuit = threading.Event()
        self.timeToQuit.clear()
        self.system_mouse_pos = api.GetCursorPos()

    def run(self):
        鼠窗坐标差_x = self.system_mouse_pos[0] - self.frame.GetPosition()[0]
        鼠窗坐标差_y = self.system_mouse_pos[1] - self.frame.GetPosition()[1]
        while 1:
            self.timeToQuit.wait(0.02)
            if self.timeToQuit.isSet():
                break
            self.system_mouse_pos = api.GetCursorPos()
            frame_pos_x = self.system_mouse_pos[0] - 鼠窗坐标差_x
            frame_pos_y = self.system_mouse_pos[1] - 鼠窗坐标差_y
            frame_pos = (frame_pos_x, frame_pos_y)
            wx.CallAfter(self.frame.move_start, frame_pos)
        else:
            wx.CallAfter(self.frame.move_stop, self)


class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        self.threads = []
        self.Bind(wx.EVT_CLOSE,  self.evt_close)
        panel = wx.Panel(self)
        panel.Bind(wx.EVT_LEFT_DOWN, self.evt_left_down)
        panel.Bind(wx.EVT_LEFT_UP, self.evt_left_up)

    def evt_close(self, event):
        while self.threads:
            thread = self.threads[0]
            thread.timeToQuit.set()
            self.threads.remove(thread)
        self.Destroy()

    def evt_left_down(self, event):
        thread = WorkerThread(self)
        self.threads.append(thread)
        thread.start()

    def evt_left_up(self, event):
        if self.threads:
            self.threads[0].timeToQuit.set()
            self.threads.remove(self.threads[0])

    def move_start(self, frame_pos):
        # wx.MilliSleep(2)
        self.SetPosition(frame_pos)

    def move_stop(self, thread):
        self.threads.remove(thread)


def main():
    app = wx.App()
    frame = MyFrame(None)
    frame.Show()
    app.MainLoop()


if __name__ == "__main__":
    main()

你可能感兴趣的:(python: 用threading实现获取屏幕鼠标位置用于拖动wxpython的窗口)