Created
August 31, 2022 10:00
-
-
Save j1o1h1n/40e153ba7a05e733f983913499457de6 to your computer and use it in GitHub Desktop.
A dictionary TUI written in python using the textual library - see https://asciinema.org/a/518081
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Button { | |
padding-left: 1; | |
padding-right: 1; | |
} | |
TextInput { | |
layout: horizontal; | |
height: 3; | |
background: $panel-darken-1; | |
border: tall $panel-darken-2; | |
margin: 1; | |
padding: 0 1; | |
} | |
TextInput.running { | |
color: #839496; | |
text-style: italic; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import wordbook | |
from textual.app import App, events | |
from textual.widgets import Header, Footer, Static | |
from textual.widgets.text_input import TextInput, TextWidgetBase, TextArea | |
from rich.text import Text | |
import re | |
class WordsApp(App[str]): | |
async def on_mount(self) -> None: | |
"""Called when widget is first added.""" | |
self.wb = wordbook.WordBook(host="dict.org", | |
port=2628, | |
database="wn", | |
strategy="exact") | |
self.connected = False | |
def compose(self): | |
yield Header() | |
yield TextInput(placeholder="Lookup a word", id="lookup") | |
yield Static(renderable="") | |
yield Footer() | |
async def _on_key(self, event: events.Key) -> None: | |
if event.key == "tab": | |
self.focus_next() | |
elif event.key == "shift+tab": | |
self.focus_previous() | |
else: | |
await self.press(event.key) | |
async def on_text_input_submitted(self, event: TextInput.Submitted) -> None: | |
value = event.value | |
static = self.query_one(Static) | |
self.log("Lookup", value) | |
self.query_one(TextInput).add_class("running") | |
if not self.connected: | |
await self.wb.connect() | |
self.connected = True | |
lines = await self.wb.define(value) | |
self.query_one(TextInput).remove_class("running") | |
if lines: | |
footer = re.findall('"([^"]+)"', lines[0])[-1] | |
self.log(repr(lines[0])) | |
text = Text.assemble((lines[1], "bold"), | |
"\n", | |
"\n".join(lines[2:]), | |
"\n\n", | |
(footer, "italic")) | |
static.update(text) | |
else: | |
static.update(Text(f"The word {value} was not found", style="italic #93a1a1")) | |
app = WordsApp( | |
log_path="textual.log", css_path="words.css", watch_css=True, log_verbosity=2, title="Words" | |
) | |
if __name__ == "__main__": | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment