Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A slider for curses based UI

As a learning project, I'd like to set-out to make an ncurses-based UI for a program I had in mind, written in python.

After looking at urwid documentation, I cannot see anyway to create a simple slider (I need it to make a volume slider) that can be adjusted with the mouse.

Am I missing something in urwid, or is there a more convenient curses module to make such a slider?

like image 249
Fruckubus Crunt Avatar asked Nov 24 '11 01:11

Fruckubus Crunt


1 Answers

Curses is has very low level API - going back to the 1980's C'programing.

The Python wrappers have some higher level support for keyboard input and some other niceties, but they are few and apart and not nicely documented.

The Python niceties do not include Mouse support (ok, you get your mouse state back in a tuple instead of having to create a C structure for that, so it is somewhat better).

The idea is that one has to enable a curses Window enable "keypad" so that Python gives you full key codes enable a "mousemask" so that mouse events are sent to your app Detect the special "mouse_key" keyboard code in the getch function so that you can call "getmouse" to get the coordinates and button state.

So there are no pre-made nice callbacks, you have to set-up the mainloop of your application to detect mouse events your self.

This sample code performs the above steps for reading the mouse events and printing the mouse state to the screen - it should be enough to get one started in building some usefull mouse handling with curses:

# -*- coding: utf-8 -*-
import curses

screen = curses.initscr()
curses.noecho()
curses.mousemask(curses.ALL_MOUSE_EVENTS)

screen.keypad(1)

char = ""

try:
    while True:
        char = screen.getch()

        screen.addstr( str(char) + " ")
        if char == curses.KEY_MOUSE:
            screen.addstr (" |" + str(curses.getmouse()) + "| ")

finally:
    screen.keypad(0)
    curses.endwin()

    curses.echo()
like image 172
jsbueno Avatar answered Oct 15 '22 04:10

jsbueno