import curses 

screen = curses.initscr() 
#curses.noecho() 
curses.curs_set(0) 
screen.keypad(1) 
curses.mousemask(1)

screen.addstr("This is a Sample Curses Script\n\n") 

while True:
    event = screen.getch() 
    if event == ord("q"): break 
    if event == curses.KEY_MOUSE:
        _, mx, my, _, _ = curses.getmouse()
        y, x = screen.getyx()
        screen.addstr(y, x, screen.instr(my, mx, 5))

curses.endwin()

You should read the docs more carefully, it's all in there :-)

Answer from Irfy on Stack Overflow
🌐
Python
docs.python.org › 3 › library › curses.html
curses — Terminal handling for character-cell displays
Push a KEY_MOUSE event onto the input queue, associating the given state data with it. ... If used, this function should be called before initscr() or newterm are called. When flag is False, the values of lines and columns specified in the terminfo database will be used, even if environment variables LINES and COLUMNS (used by default) are set, or if curses is running in a window (in which case default behavior would be to use the window size if LINES and COLUMNS are not set).
🌐
Reddit
reddit.com › r/learnpython › how to make python curses register mouse movement events?
r/learnpython on Reddit: How to make python curses register mouse movement events?
November 3, 2019 -

It seems that I only get the mouse location when the mouse is clicked and unclicked. I want to implement a sort of drag and drop, and I need to know where the mouse is during the drag. I tried the following (where I get the mouse positoin regardless if I got a KEY_MOUSE or not, but getmouse() reports an ERR (without much explanation)

    curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)
    while(True):
        event = screen.getch()
        ch = 'N'
        if event == ord('q'): break
        elif event == curses.KEY_MOUSE:
            ch = 'Y'
        _, mx, my, _, _ = curses.getmouse()
        screen.addstr(my, mx, ch)

I did find this asked on stack overflow 5 months ago, but nobody answered. I'm starting to fear that python/curses doesn't support this.

🌐
Python documentation
docs.python.org › 3 › howto › curses.html
Curses Programming with Python — Python 3.14.4 documentation
The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals; such terminals include VT100s, the Linux console, and the simulated terminal provided by various programs. Display terminals support various control codes to perform common operations such as moving the cursor, scrolling the screen, and erasing areas.
🌐
ProgramCreek
programcreek.com › python › example › 7635 › curses.getmouse
Python Examples of curses.getmouse
def on_mouse(): '''Update selected line / sort''' _, x, y, z, bstate = curses.getmouse() # Left button click ? if bstate & curses.BUTTON1_CLICKED: # Is it title line ? if y == 0: # Determine sort column based on offset / col width x_max = 0 return 2 # Is it a cgroup line ? return 1 ... def safe_get_mouse_event(self): try: mouse_event = curses.getmouse() return mouse_event except _curses.error: return None
Top answer
1 of 2
4

I know this is a pretty old question and the OP might not need it anymore, but I'm leaving it here for anyone who stumbles upon this question after hours of googling and head scratching:

import curses

def main(win:curses.window):
    win.clear()
    win.nodelay(True)
    curses.mousemask(curses.REPORT_MOUSE_POSITION)
    print('\033[?1003h') # enable mouse tracking with the XTERM API
    # https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Mouse-Tracking

    while True:
        ch=win.getch()
        if ch==curses.KEY_MOUSE:
            win.clear()
            win.addstr(0,0,str(curses.getmouse()[1:3]))
            win.refresh()

curses.wrapper(main)

The most important line here is the print('\033[?1003h'), which enables the mouse position reporting to the program, while the mousemask enables curses to interpret the input from the terminal. Note that the print must appear after the mousemask() is called.

Tested on macOS 10.14.6 with iTerm2. There is no tweak to the terminfo.

2 of 2
2

I finally got it to work. On Ubuntu it worked by simply setting TERM=screen-256color, but on OSX I had to edit a terminfo file, using the instructions here:

Which $TERM to use to have both 256 colors and mouse move events in python curses?

but on my system the format was different so I added the line:

XM=\E[?1003%?%p1%{1}%=%th%el%;,

to my terminfo. To test it, I used this Python code (note screen.keypad(1) is very necessary, otherwise mouse events cause getch to return escape key codes).

import curses

screen = curses.initscr()
screen.keypad(1)
curses.curs_set(0)
curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION)
curses.flushinp()
curses.noecho()
screen.clear()

while True:
    key = screen.getch()
    screen.clear()
    screen.addstr(0, 0, 'key: {}'.format(key))
    if key == curses.KEY_MOUSE:
        _, x, y, _, button = curses.getmouse()
        screen.addstr(1, 0, 'x, y, button = {}, {}, {}'.format(x, y, button))
    elif key == 27:
        break

curses.endwin()
curses.flushinp()
🌐
YouTube
youtube.com › indian pythonista
Handling Mouse Events on Terminal | Intro to curses in Python (Part-4) - YouTube
Welcome to the 4th video of my tutorial series on "curses in Python". Learn how to handle mouse click events on terminal in a curses application with simple ...
Published   March 27, 2019
Views   12K
Find elsewhere
🌐
GitHub
github.com › nikhilkumarsingh › python-curses-tut › blob › master › 04. Handling Mouse Events.ipynb
python-curses-tut/04. Handling Mouse Events.ipynb at master · nikhilkumarsingh/python-curses-tut
A beginners guide to curses in Python. Contribute to nikhilkumarsingh/python-curses-tut development by creating an account on GitHub.
Author   nikhilkumarsingh
🌐
HotExamples
python.hotexamples.com › examples › curses › - › getmouse › python-getmouse-function-examples.html
Python getmouse Examples, curses.getmouse Python Examples - HotExamples
These are the top rated real world Python examples of curses.getmouse extracted from open source projects. You can rate examples to help us improve the quality of examples. ... def main(t): curses.curs_set(0) a, b = curses.mousemask(curses.ALL_MOUSE_EVENTS | curses.REPORT_MOUSE_POSITION) t.addstr(2, 0, f"a={a}, b={b}") pt = Point() curses.delay_output(100) mx, my = 0, 0 while True: # draw t.addstr(0, 0, f"x={mx}, y={my}") a, mx, my, _, mask = curses.getmouse() t.addstr(4, 0, f"x={pt.x}, y={pt.y}") # input windll.user32.GetCursorPos(byref(pt)) c = t.getch() if c == ord('q'): break if c == curses.KEY_MOUSE: t.addstr(1, 0, "MOUSE") a, mx, my, _, mask = curses.getmouse()
🌐
Narkive
comp.lang.python.narkive.com › eci7hz9r › python-curses-constant-names-for-mouse-wheel-movements
python curses constant names for mouse wheel movements?
December 21, 2020 - DEBUG:root:wch='539' = 0x021b at (0,0) DEBUG:root:3ch='KEY_MOUSE at (0,0)' DEBUG:root:3ch KEY_MOUSE detected at (0,0) DEBUG:root:Mouse data id=0, x=60, y=31, z=0, bs=00000004 Button 1 click DEBUG:root:wch='539' = 0x021b at (0,0) DEBUG:root:3ch='KEY_MOUSE at (0,0)' DEBUG:root:3ch KEY_MOUSE detected at (0,0) DEBUG:root:Mouse data id=0, x=-1, y=-1, z=0, bs=00010000 wheel up once DEBUG:root:wch='539' = 0x021b at (0,0) DEBUG:root:3ch='KEY_MOUSE at (0,0)' DEBUG:root:3ch KEY_MOUSE detected at (0,0) DEBUG:root:Mouse data id=0, x=-1, y=-1, z=0, bs=00200000 wheel down once DEBUG:root:wch='539' = 0x021b
🌐
Ucdavis
heather.cs.ucdavis.edu › ~matloff › Python › PLN › PyCurses.tex
Examples of Python Curses Programs
st do in response to various user commands, such as the following (suppose our window object is {\bf scrn}): \begin{itemize} \item {\bf k} command, to move the cursor up one line: might call {\bf scrn.move(r,c)}, which moves the {\tt curses} cursor to the specified row and column\footnote{But if the movement causes a scrolling operation, other {\tt curses} functions will need to be called too.} \item {\bf dd} command, to delete a line: might call {\bf scrn.deleteln()}, which causes the current row to be deleted and makes the rows below move up\footnote{But again, things would be more complicat
🌐
Stack Overflow
stackoverflow.com › questions › 52393234 › curses-isnt-registering-mouse-clicks-in-python › 52395211
Curses isn't registering mouse clicks in Python - Stack Overflow
Found out why it wasn't working. I just added curses.mousemask(curses.BUTTON1_CLICKED) before w.nodelay(False) and w.keypad(True) after w.nodelay(False). ... long: Python curses uses ncurses to get the mouse events.
🌐
Read the Docs
python.readthedocs.io › en › latest › library › curses.html
16.10. curses — Terminal handling for character-cell displays
Push a KEY_MOUSE event onto the input queue, associating the given state data with it. ... If used, this function should be called before initscr() or newterm are called. When flag is False, the values of lines and columns specified in the terminfo database will be used, even if environment variables LINES and COLUMNS (used by default) are set, or if curses is running in a window (in which case default behavior would be to use the window size if LINES and COLUMNS are not set).
🌐
OMZ Software
omz-software.com › editorial › docs › howto › curses.html
Curses Programming with Python — Editorial Documentation
The Console module provides cursor-addressable text output, plus full support for mouse and keyboard input, and is available from http://effbot.org/zone/console-index.htm. Thy Python module is a fairly simple wrapper over the C functions provided by curses; if you’re already familiar with curses programming in C, it’s really easy to transfer that knowledge to Python.
🌐
Python
docs.python.org › 3.7 › howto › curses.html
Curses Programming with Python — Python 3.7.17 documentation
The curses library supplies a terminal-independent screen-painting and keyboard-handling facility for text-based terminals; such terminals include VT100s, the Linux console, and the simulated terminal provided by various programs. Display terminals support various control codes to perform common operations such as moving the cursor, scrolling the screen, and erasing areas.
🌐
Python
docs.python.org › 3.5 › howto › curses.html
Curses Programming with Python — Python 3.5.10 documentation
The Windows version of Python doesn’t include the curses module. A ported version called UniCurses is available. You could also try the Console module written by Fredrik Lundh, which doesn’t use the same API as curses but provides cursor-addressable text output and full support for mouse and keyboard input.