dictionary example

This commit is contained in:
Will McGugan
2022-09-18 15:43:47 +01:00
parent 743b43a6c2
commit 4e732ce309
12 changed files with 205 additions and 45 deletions

View File

@@ -0,0 +1,43 @@
import asyncio
try:
import httpx
except ImportError:
raise ImportError("Please install http with 'pip install httpx' ")
from rich.json import JSON
from textual.app import App, ComposeResult
from textual.layout import Vertical
from textual.widgets import Static, TextInput
class DictionaryApp(App):
"""Searches ab dictionary API as-you-type."""
def compose(self) -> ComposeResult:
yield TextInput(placeholder="Search for a word")
yield Vertical(Static(id="results", fluid=False), id="results-container")
async def on_text_input_changed(self, message: TextInput.Changed) -> None:
"""A coroutine to handle a text changed message."""
if message.value:
# Look up the word in the background
asyncio.create_task(self.lookup_word(message.value))
else:
# Clear the results
self.query_one("#results", Static).update()
async def lookup_word(self, word: str) -> None:
"""Looks up a word."""
url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}"
async with httpx.AsyncClient() as client:
results = (await client.get(url)).text
if word == self.query_one(TextInput).value:
self.query_one("#results", Static).update(JSON(results))
app = DictionaryApp(css_path="dictionary.css")
if __name__ == "__main__":
app.run()