magikarp
magikarp

Reputation: 470

Keypress not working for Edit widget in Urwid

I'm trying to make a terminal application in Python using Urwid.

import urwid
class Guess():
    def __init__(self):
        self.guess = urwid.Edit(align='center')

    def keypress(self, size, key):
        if key.lower() == 'enter':
            user_guess = self.guess.edit_text
            self.guess.edit_text = " "
            self.check_guess(user_guess)

This is the part where I need input from the user which I then need to send to another function.

The documentation for the keypress() method is not at all helpful. I looked at other people's codes, and I tried it using the above, along with a few other ways I found while surfing the internet but got no luck.

Could someone explain to me the exact functioning of the keypress() method and how I can achieve what I wan?

Upvotes: 2

Views: 355

Answers (2)

Gang
Gang

Reputation: 2768

keypress is internal method of Edit class, this

class Guess():
    def __init__(self):
        self.guess = urwid.Edit(align='center')

has to be changed to this to be able to inherit from Edit

class Guess(urwid.Filler)

This your own keypress implemenation has to inherit from Edit, change from

def keypress(self, size, key):
    if key.lower() == 'enter':

to this

    # keep same behavior as in keypress in Edit
    return super(Guess, self).keypress(size, key)

The whole program will like this

import urwid


def exit_on_q(key):
    if key in ('q', 'Q'):
        raise urwid.ExitMainLoop()


# class is inheritance of Filler class Edit
class Guess(urwid.Filler):

    def keypress(self, size, key):
        if key.lower() == 'enter':
            # your own implementation of keypress after enter
            user_guess = guess.edit_text
            self.original_widget = urwid.Text('your guess: {},     Q(q)uit'.format(user_guess))
            return
        # keep same behavior as in keypress in Edit
        return super(Guess, self).keypress(size, key)


# Edit(with internal keypress()
guess = urwid.Edit('guess who?', align='center')
filler = Guess(guess)
loop = urwid.MainLoop(filler, unhandled_input=exit_on_q)
loop.run()

Upvotes: 0

Mohideen bin Mohammed
Mohideen bin Mohammed

Reputation: 20137

urwid is Console user interface library for Python.

if you want to trace kyepress try below,

pip install keyboard

import keyboard # using module keyboard

def keypress(self, size, key):
    if keyboard.is_pressed('enter'):
        user_guess = self.guess.edit_text
        self.guess.edit_text = " "
        self.check_guess(user_guess)

Upvotes: 0

Related Questions