杰瑞科技汇

Python movecursor如何实现鼠标移动控制?

Of course! Moving the cursor in Python is a common task for creating command-line applications, games, or simple text-based user interfaces. The best method depends on your operating system (Windows, macOS, Linux).

Python movecursor如何实现鼠标移动控制?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the most popular and effective ways to do it.

Summary: Which Method Should I Use?

Method Best For Pros Cons
curses Robust TUIs (Text User Interfaces) Cross-platform, powerful, handles screen drawing Steeper learning curve, not for simple scripts
pyautogui GUI Automation, Cross-platform scripts Extremely easy, cross-platform, does more than just cursors Requires an external library, can be slow
ANSI Codes Quick, simple scripts on Linux/macOS Built-in (no imports), lightweight Not supported by default on Windows CMD
msvcrt Windows-only scripts, simple movement Built-in, very fast on Windows Windows-only, limited functionality

Method 1: The curses Library (Recommended for TUIs)

The curses library is the standard way to create rich, interactive command-line applications. It's designed to give you precise control over the terminal, including cursor movement, reading key presses, and drawing text boxes.

It's built into Python on Linux and macOS, but you may need to install it on Windows.

Installation on Windows:

Python movecursor如何实现鼠标移动控制?-图2
(图片来源网络,侵删)
pip install windows-curses

How it works: You initialize the screen, then use functions like stdscr.move(y, x) to position the cursor.

Example: Moving and Printing

import curses
import time
def main(stdscr):
    # Turn off cursor visibility
    curses.curs_set(0)
    # Get the size of the terminal
    height, width = stdscr.getmaxyx()
    # Move the cursor to the center of the screen
    center_y = height // 2
    center_x = width // 2
    stdscr.move(center_y, center_x)
    stdscr.addstr("Hello from the center!")
    stdscr.refresh()
    time.sleep(2)
    # Move the cursor and print more text
    stdscr.move(center_y + 1, center_x - 10)
    stdscr.addstr("This is below and to the left.")
    stdscr.refresh()
    time.sleep(2)
    # Clear the screen and move the cursor to the top-left
    stdscr.clear()
    stdscr.move(0, 0)
    stdscr.addstr("Cursor is now at (0, 0). Press any key to exit.")
    stdscr.refresh()
    # Wait for a key press to exit
    stdscr.getch()
if __name__ == "__main__":
    curses.wrapper(main)

To run this, save it as curses_example.py and execute it from your terminal.


Method 2: The pyautogui Library (Easiest & Most Powerful)

pyautogui is a fantastic library for automating GUI interactions. While its primary focus is controlling the mouse and keyboard, it can also move the text cursor within a terminal or text editor. It's incredibly easy to use and cross-platform.

Python movecursor如何实现鼠标移动控制?-图3
(图片来源网络,侵删)

Installation:

pip install pyautogui

How it works: You simply import the library and call pyautogui.moveTo() or pyautogui.typewrite().

Example: Moving the Cursor and Typing

import pyautogui
import time
# Note: This script will control your actual mouse and keyboard.
# Be careful not to move your mouse while it's running, or it might get stuck.
# Add a failsafe: move mouse to top-left corner to stop the script.
pyautogui.FAILSAFE = True
print("Script will start in 5 seconds. Move your mouse to the top-left corner to stop.")
time.sleep(5)
# Move the mouse cursor to a specific position (x, y)
# You'll need to find the coordinates of your terminal window first.
# On macOS/Linux, you can use 'xdotool getmouselocation' or similar tools.
# On Windows, you can use PowerShell or a third-party tool.
# For this example, let's assume the terminal is at (500, 300).
pyautogui.moveTo(500, 300, duration=1.0) # duration makes the move smooth
print("Cursor moved to (500, 300)")
# Type some text at the new cursor location
time.sleep(1)
pyautogui.typewrite("Hello from pyautogui!", interval=0.1)
print("Text typed.")
# You can also use relative movements
time.sleep(2)
pyautogui.moveRel(100, 50, duration=0.5) # Move 100 pixels right, 50 down
print("Cursor moved relatively.")
pyautogui.typewline("This is on a new line.")

Method 3: ANSI Escape Codes (Built-in for Linux/macOS)

Modern terminal emulators on Linux and macOS understand ANSI escape codes. These are special sequences of characters that you can print to the terminal to control its behavior, including moving the cursor.

How it works: You print a string like \033[y;xH where y is the row and x is the column. \033[ is the escape character.

Example: Using ANSI Codes

import time
import sys
import os
# This method only works on terminals that support ANSI codes.
# Most modern Linux/macOS terminals do. Windows CMD does not by default.
# Clear the screen (ANSI code for clear)
print("\033[2J", end="")
# Move cursor to home position (0, 0)
print("\033[H", end="")
print("This is at the top-left corner.")
# ANSI code to move cursor: \033[y;xH
# y=5, x=10
print("\033[5;10H", end="")
print("This text is at row 5, column 10.")
time.sleep(2)
# Move cursor down one line and to the right 5 columns from current position
print("\033[1;5B", end="") # B = Down, C = Right, A = Up, D = Left
print("This is one line down and 5 columns to the right.")
# For Windows 10/11, you might need to enable ANSI support first:
# os.system('') # This can enable ANSI support in some Windows environments

Method 4: msvcrt (Windows-Only)

On Windows, you can use the msvcrt module, which provides access to the Microsoft Visual C++ runtime library. It has a function to set the cursor position in the console.

How it works: You call msvcrt.getwch() to get the current console handle, then use a Windows API call via ctypes to set the position.

Example: Windows msvcrt

import msvcrt
import ctypes
import time
# Define the Windows API function
GetStdHandle = ctypes.windll.kernel32.GetStdHandle
SetConsoleCursorPosition = ctypes.windll.kernel32.SetConsoleCursorPosition
STD_OUTPUT_HANDLE = -11
# Get a handle to the console
h_out = GetStdHandle(STD_OUTPUT_HANDLE)
def move_cursor(x, y):
    """Moves the console cursor to the specified position (x, y)."""
    # Windows uses COORD structure for cursor position
    # y is the row, x is the column
    coord = ctypes.c_ushort(x)
    coord.y = y
    SetConsoleCursorPosition(h_out, coord)
# Clear the screen
print("cls", end='\r')
os.system('cls')
print("This is at the default position.")
time.sleep(2)
# Move to column 20, row 5
move_cursor(20, 5)
print("This is at (20, 5).")
time.sleep(2)
# Move to column 0, row 10
move_cursor(0, 10)
print("This is at the far left, 10 lines down.")

How to Clear the Screen

Moving the cursor is often more useful when you can also clear the screen. Here's how to do it for each method:

Method Clear Screen Command
curses stdscr.clear() then stdscr.refresh()
pyautogui os.system('cls') (Windows) or os.system('clear') (Linux/macOS)
ANSI Codes print("\033[2J", end="")
msvcrt os.system('cls')
分享:
扫描分享到社交APP
上一篇
下一篇