Introduction to Textual
Textual is a modern TUI (Text User Interface) framework for Python. It allows developers to create beautiful and functional text-based applications in the terminal with ease. With its intuitive API and rich feature set, Textual is perfect for creating command-line tools, dashboards, and much more.
Getting Started
First, install Textual using pip:
pip install textual
Basic Concepts
Textual applications are composed of widgets. Widgets are the building blocks of a Textual interface and can be anything from a simple button to a complex layout.
Creating a Simple Application
Let’s start by creating a simple Textual app:
from textual.app import App
from textual.widgets import Placeholder
class SimpleApp(App):
async def on_mount(self):
await self.view.dock(Placeholder(name="Hello, world!"))
if __name__ == "__main__":
SimpleApp.run()
Working with Widgets
Textual comes with a variety of widgets that you can use to build your interface:
Button Widget
from textual.widgets import Button
button = Button(label="Click Me")
Text Input Widget
from textual.widgets import TextInput
text_input = TextInput(placeholder="Enter text here")
Label Widget
from textual.widgets import Label
label = Label(text="This is a label")
Layout Management
Textual provides powerful layout management with widgets like Dock
and Grid
:
Dock Layout
await self.view.dock(header, edge="top")
await self.view.dock(footer, edge="bottom")
Grid Layout
await self.view.dock(grid=Grid(gap=2, columns=[1, 2, 1]), edge="top")
Events and Actions
Handling events in Textual is straightforward. You can define event handlers in your widget classes:
from textual.app import App
from textual.widgets import Button
class MyButton(Button):
async def on_click(self):
print("Button clicked!")
class MyApp(App):
async def on_mount(self):
await self.view.dock(MyButton(label="Click Me"))
if __name__ == "__main__":
MyApp.run()
An Example App
Here’s an example app that puts everything together:
from textual.app import App
from textual.widgets import Header, Footer, Button, TextInput, Label
class ExampleApp(App):
async def on_mount(self):
header = Header()
footer = Footer()
button = Button(label="Press Me")
text_input = TextInput(placeholder="Type something")
label = Label(text="Enter some text above")
await self.view.dock(header, edge="top")
await self.view.dock(footer, edge="bottom")
await self.view.dock(button, edge="left", size=20)
await self.view.dock(text_input, edge="top")
await self.view.dock(label, edge="top")
button.on_click = lambda: self.on_button_click()
async def on_button_click(self):
print("Button was clicked!")
if __name__ == "__main__":
ExampleApp.run()
With these examples, you should be well on your way to creating impressive text-based applications using Textual. Happy coding!
Hash: 8c7399664b5f87a56ca51c0f790857da211e474520a7309c36c28ae8b49485c9