【问题标题】:Python script to control mouse clicks控制鼠标点击的 Python 脚本
【发布时间】:2013-09-29 18:59:10
【问题描述】:

我使用 win32api 创建了一个小 Python 脚本,用于流行游戏 Cookie Clicker(您必须点击大饼干才能获得积分的游戏),只是为了好玩。它有一个名为“auto_clicker”的功能,它可以做到这一点:在用户定义的点上不断点击屏幕。这是脚本:

# -*- coding: utf-8 -*-

import win32con
import win32api

def clicker(x,y):
    """Clicks on given position x,y

    Input:
    x -- Horizontal position in pixels, starts from top-left position
    y -- Vertical position in pixels, start from top-left position

    """

    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

def auto_clicker(x = -1,y = -1):
    """Keep clicking on position x,y. If no input is given, gets from actual
    mouse position.

    """
    if x == -1 | y == -1:
        x,y = win32api.GetCursorPos()
    while True:
        clicker(x,y)

效果很好,但我想进行一些改进:

  • 如何在调用函数时仅在用户单击而不是单击时获取光标位置?我宁愿不添加另一个模块 因为 win32api 似乎包含了我需要的一切。试过this 方法没有成功。

  • 如何检测像“Escape”这样的按键,这样我就可以退出我的程序,而无需我现在正在使用的丑陋 hack(Ctrl+Alt+Del 似乎给 SetCursorPos 拒绝访问,所以 Python 会抛出一个错误并退出程序)。

  • 我可以使这个程序可移植吗?似乎我可以使用 Tkinter 并生成一个不可见的 Tk 窗口,但我试图写一些没有成功的东西。

【问题讨论】:

    标签: python keyboard tkinter mouseevent pywin32


    【解决方案1】:

    我不认为使用 win32api 你可以听到点击你可以生成它们(虽然不确定)。但是,尝试使用 pyHook,它是一个简单易用的 api,可以在这里找到http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=Main_Page。使用 pyhook,您可以创建一个侦听器来侦听鼠标事件,并且在单击鼠标时您可以做任何您想做的事情,链接中的示例向您展示了如何操作。至于按键,你也可以使用相同的api,还提供了一个例子,祝你好运!

    【讨论】:

      【解决方案2】:

      使用 pynput 。可以控制鼠标、键盘等。

      例子:

      from pynput.mouse import Button, Controller
      
      mouse = Controller()
      
      # Read pointer position
      print('The current pointer position is {0}'.format(
          mouse.position))
      
      # Set pointer position
      mouse.position = (10, 20)
      print('Now we have moved it to {0}'.format(
          mouse.position))
      
      # Move pointer relative to current position
      mouse.move(5, -5)
      
      # Press and release
      mouse.press(Button.left)
      mouse.release(Button.left)
      
      # Double click; this is different from pressing and releasing
      # twice on Mac OSX
      mouse.click(Button.left, 2)
      
      # Scroll two steps down
      mouse.scroll(0, 2)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-15
        • 2019-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-11
        • 2010-11-13
        相关资源
        最近更新 更多