如何在Python-Curses中启用小鼠运动事件



我想用python-curses检测鼠标运动事件。我不知道如何启用这些事件。我试图启用所有鼠标事件,如下所示:

stdscr = curses.initscr()
curses.mousemask(curses.REPORT_MOUSE_POSITION | curses.ALL_MOUSE_EVENTS)
while True:
    c = stdscr.getch()
    if c == curses.KEY_MOUSE:
        id, x, y, z, bstate = curses.getmouse()
        stdscr.addstr(curses.LINES-2, 0, "x: " + str(x))
        stdscr.addstr(curses.LINES-1, 0, "y: " + str(y))
        stdscr.refresh()
    if c == ord('q'):
        break
 curses.endwin()

我只有在单击鼠标按钮,推入等时才能获得鼠标事件,但没有鼠标移动事件。我如何启用这些事件?

我通过更改我的$ term env var/terminfo来使它起作用。在Ubuntu上,它可以通过简单地设置TERM=screen-256color来工作,但是在OSX上,我必须在此处使用指令编辑terminfo文件:

在Python诅咒中同时使用256种颜色和鼠标移动事件?

但对我而言,格式不同,所以我添加了行:

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

要测试它,我使用了此Python代码(注意screen.keypad(1)非常必要,否则鼠标事件会导致getch返回逃生密钥代码(。

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()

最新更新