File: multiple.py

package info (click to toggle)
urwid 3.0.4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,232 kB
  • sloc: python: 29,010; javascript: 382; sh: 34; makefile: 22
file content (36 lines) | stat: -rw-r--r-- 1,027 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from __future__ import annotations

import urwid


def question():
    return urwid.Pile([urwid.Edit(("I say", "What is your name?\n"))])


def answer(name):
    return urwid.Text(("I say", f"Nice to meet you, {name}\n"))


class ConversationListBox(urwid.ListBox):
    def __init__(self) -> None:
        body = urwid.SimpleFocusListWalker([question()])
        super().__init__(body)

    def keypress(self, size: tuple[int, int], key: str) -> str | None:
        key = super().keypress(size, key)
        if key != "enter":
            return key
        name = self.focus[0].edit_text
        if not name:
            raise urwid.ExitMainLoop()
        # replace or add response
        self.focus.contents[1:] = [(answer(name), self.focus.options())]
        pos = self.focus_position
        # add a new question
        self.body.insert(pos + 1, question())
        self.focus_position = pos + 1
        return None


palette = [("I say", "default,bold", "default")]
urwid.MainLoop(ConversationListBox(), palette).run()