renamed introduction to tutorial

This commit is contained in:
Will McGugan
2022-09-05 21:30:29 +01:00
parent 54539a90d1
commit e7d57a4aa2
28 changed files with 182 additions and 67 deletions

View File

@@ -0,0 +1,17 @@
Screen {
layout: table;
table-size: 2;
table-gutter: 2;
padding: 2;
}
#question {
width: 100%;
height: 100%;
column-span: 2;
content-align: center bottom;
text-style: bold;
}
Button {
width: 100%;
}

View File

@@ -4,17 +4,15 @@ from textual.widgets import Static, Button
class QuestionApp(App[str]): class QuestionApp(App[str]):
def compose(self) -> ComposeResult: def compose(self) -> ComposeResult:
yield Static("Do you love Textual?") yield Static("Do you love Textual?", id="question")
yes = yield Button("Yes", id="yes") yield Button("Yes", id="yes", variant="primary")
yes.variant = "primary" yield Button("No", id="no", variant="error")
no = yield Button("No", id="no")
no.variant = "error"
def on_button_pressed(self, event: Button.Pressed) -> None: def on_button_pressed(self, event: Button.Pressed) -> None:
self.exit(event.button.id) self.exit(event.button.id)
app = QuestionApp() app = QuestionApp(css_path="question02.css")
if __name__ == "__main__": if __name__ == "__main__":
reply = app.run() reply = app.run()
print(reply) print(reply)

View File

@@ -0,0 +1,38 @@
from textual.app import App, ComposeResult
from textual.widgets import Static, Button
class QuestionApp(App[str]):
CSS = """
Screen {
layout: table;
table-size: 2;
table-gutter: 2;
padding: 2;
}
#question {
width: 100%;
height: 100%;
column-span: 2;
content-align: center bottom;
text-style: bold;
}
Button {
width: 100%;
}
"""
def compose(self) -> ComposeResult:
yield Static("Do you love Textual?", id="question")
yield Button("Yes", id="yes", variant="primary")
yield Button("No", id="no", variant="error")
def on_button_pressed(self, event: Button.Pressed) -> None:
self.exit(event.button.id)
app = QuestionApp()
if __name__ == "__main__":
reply = app.run()
print(reply)

View File

@@ -10,7 +10,7 @@ CSS stands for _Cascading Stylesheets_. A stylesheet is a list of styles and rul
Depending on what you want to build with Textual, you may not need to learn Textual CSS at all. Widgets are packaged with CSS styles so apps with exclusively pre-built widgets may not need any additional CSS. Depending on what you want to build with Textual, you may not need to learn Textual CSS at all. Widgets are packaged with CSS styles so apps with exclusively pre-built widgets may not need any additional CSS.
Textual CSS defines a set of rules which apply visual _styles_ to your application and widgets. These style can customize a large variety of visual settings, such as color, border, size, alignment; and more dynamic features such as animation and hover effects. As powerful as it is, CSS in Textual is quite straightforward. Textual CSS defines a set of rules which apply visual _styles_ to your application and widgets. These style can customize settings for properties such as color, border, size, alignment; and more dynamic features such as animation and hover effects. As powerful as it is, CSS in Textual is quite straightforward.
CSS is typically stored in an external file with the extension `.css` alongside your Python code. CSS is typically stored in an external file with the extension `.css` alongside your Python code.
@@ -30,7 +30,7 @@ This is an example of a CSS _rule set_. There may be many such sections in any g
Let's break this CSS code down a bit. Let's break this CSS code down a bit.
```css hl_lines="1" ```sass hl_lines="1"
Header { Header {
dock: top; dock: top;
height: 3; height: 3;
@@ -42,7 +42,7 @@ Header {
The first line is a _selector_ which tells Textual which Widget(s) to modify. In the above example, the styles will be applied to a widget defined by the Python class `Header`. The first line is a _selector_ which tells Textual which Widget(s) to modify. In the above example, the styles will be applied to a widget defined by the Python class `Header`.
```css hl_lines="2 3 4 5 6" ```sass hl_lines="2 3 4 5 6"
Header { Header {
dock: top; dock: top;
height: 3; height: 3;
@@ -58,7 +58,7 @@ The first rule in the above example reads `"dock: top;"`. The rule name is `dock
## The DOM ## The DOM
The DOM, or _Document Object Model_, is a term borrowed from the web world. Textual doesn't use documents but the term has stuck. In Textual CSS, the DOM is a an arrangement of widgets you can visualize as a tree-like structure. The DOM, or _Document Object Model_, is a term borrowed from the web world. Textual doesn't use documents but the term has stuck. In Textual CSS, the DOM is an arrangement of widgets you can visualize as a tree-like structure.
Some widgets contain other widgets: for instance, a list control widget will likely also have item widgets, or a dialog widget may contain button widgets. These _child_ widgets form the branches of the tree. Some widgets contain other widgets: for instance, a list control widget will likely also have item widgets, or a dialog widget may contain button widgets. These _child_ widgets form the branches of the tree.

1
docs/guide/actions.md Normal file
View File

@@ -0,0 +1 @@
# Actions

View File

@@ -1,6 +1,6 @@
# App Basics # App Basics
In this chapter we will cover what you will need to know to build a Textual application. Just enough to get you up to speed. We will go in to more detail in the following chapters. In this chapter we will cover how to use Textual's App class to create an application. Just enough to get you up to speed. We will go in to more detail in the following chapters.
## The App class ## The App class
@@ -26,20 +26,24 @@ Apps don't get much simpler than this—don't expect it to do much.
If we run this app with `python simple02.py` you will see a blank terminal, something like the following: If we run this app with `python simple02.py` you will see a blank terminal, something like the following:
```{.textual path="docs/examples/app/simple02.py" title="simple02.py"} ```{.textual path="docs/examples/app/simple02.py"}
``` ```
When you call [App.run()][textual.app.App.run] Textual puts the terminal in to a special state called *application mode*. When in application mode, the terminal will no longer echo what you type. Textual will take over responding to user input (keyboard and mouse) and will update the visible portion of the terminal (i.e. the *screen*). When you call [App.run()][textual.app.App.run] Textual puts the terminal in to a special state called *application mode*. When in application mode the terminal will no longer echo what you type. Textual will take over responding to user input (keyboard and mouse) and will update the visible portion of the terminal (i.e. the *screen*).
If you hit ++ctrl+c++ Textual will exit application mode and return you to the command prompt. Any content you had in the terminal prior to application mode will be restored. If you hit ++ctrl+c++ Textual will exit application mode and return you to the command prompt. Any content you had in the terminal prior to application mode will be restored.
## Events ## Events
Textual has an event system you can use to respond to key presses, mouse actions, and also internal state changes. Event handlers are methods which are prefixed with `on_` followed by the name of the event. Textual has an event system you can use to respond to key presses, mouse actions, and internal state changes. Event handlers are methods which are prefixed with `on_` followed by the name of the event.
One such event is the *mount* event which is sent to an application after it enters application mode. You can respond to this event by defining a method called `on_mount`. One such event is the *mount* event which is sent to an application after it enters application mode. You can respond to this event by defining a method called `on_mount`.
Another such event is `on_key` which is sent when the user presses a key. The following example contains handlers for both those events: !!! info
You may have noticed we use the term "send" and "sent" in relation to event handler methods in preference to "calling". This is because Textual uses a message passing system where events are passed (or *sent*) between components. We will cover the details in [events][events.md].
Another such event is the *key* event which is sent when the user presses a key. The following example contains handlers for both those events:
```python title="event01.py" ```python title="event01.py"
--8<-- "docs/examples/app/event01.py" --8<-- "docs/examples/app/event01.py"
@@ -50,21 +54,21 @@ The `on_mount` handler sets the `self.styles.background` attribute to `"darkblue
```{.textual path="docs/examples/app/event01.py" hl_lines="23-25"} ```{.textual path="docs/examples/app/event01.py" hl_lines="23-25"}
``` ```
The key event handler (`on_key`) specifies an `event` parameter which should be a [events.Key][textual.events.Key] instance. Every event has an associated event object which will be passed to the handler method if it is present in the method's parameter list. The key event handler (`on_key`) specifies an `event` parameter which will receive a [events.Key][textual.events.Key] instance. Every event has an associated event object which will be passed to the handler method if it is present in the method's parameter list.
!!! note !!! note
It is unusual for a method's parameters to affect how it is called. Textual accomplishes this by inspecting the method prior to calling it. It is unusual (but not unprecedented) for a method's parameters to affect how it is called. Textual accomplishes this by inspecting the method prior to calling it.
For some events, such as the key event, there is additional information on the event object. In the case of [events.Key][textual.events.Key] it will contain the key that was pressed. For some events, such as the key event, the event object contains additional information. In the case of [events.Key][textual.events.Key] it will contain the key that was pressed.
The `on_key` method above uses the `key` attribute on the Key event to change the background color if any of the keys 0-9 are pressed. The `on_key` method above uses the `key` attribute on the Key event to change the background color if any of the keys ++0++ to ++9++ are pressed.
### Async events ### Async events
Textual is powered by Python's [asyncio](https://docs.python.org/3/library/asyncio.html) framework which uses the `async` and `await` keywords to coordinate events. Textual is powered by Python's [asyncio](https://docs.python.org/3/library/asyncio.html) framework which uses the `async` and `await` keywords to coordinate events.
Textual knows to *await* your event handlers if they are generators (i.e. prefixed with the `async` keywords). Textual knows to *await* your event handlers if they are generators (i.e. prefixed with the `async` keyword).
!!! note !!! note
@@ -88,10 +92,10 @@ The following example imports a builtin Welcome widget and yields it from compos
When you run this code, Textual will *mount* the Welcome widget which contains a Markdown content area and a button: When you run this code, Textual will *mount* the Welcome widget which contains a Markdown content area and a button:
```{.textual path="docs/examples/app/widgets01.py" title="widgets01.py" } ```{.textual path="docs/examples/app/widgets01.py"}
``` ```
Notice the `on_button_pressed` method which handles the [Button.Pressed][textual.widgets.Button] event send by the button contained in the Welcome widget. The handlers calls [App.exit()][textual.app.App] to exit the app. Notice the `on_button_pressed` method which handles the [Button.Pressed][textual.widgets.Button] event sent by a button contained in the Welcome widget. The handler calls [App.exit()][textual.app.App] to exit the app.
### Mounting ### Mounting
@@ -105,7 +109,7 @@ Here's an app which adds the welcome widget in response to any key press:
When you first run this you will get a blank screen. Press any key to add the welcome widget. You can even press a key multiple times to add several widgets. When you first run this you will get a blank screen. Press any key to add the welcome widget. You can even press a key multiple times to add several widgets.
```{.textual path="docs/examples/app/widgets02.py" title="widgets02.py" press="a,a,a,down,down,down,down,down,down,_,_,_,_,_,_"} ```{.textual path="docs/examples/app/widgets02.py" press="a,a,a,down,down,down,down,down,down,_,_,_,_,_,_"}
``` ```
### Exiting ### Exiting
@@ -138,3 +142,36 @@ The addition of `[str]` tells Mypy that `run()` is expected to return a string.
!!! note !!! note
Type annotations are entirely optional (but recommended) with Textual. Type annotations are entirely optional (but recommended) with Textual.
## CSS
Textual apps can reference [CSS](CSS.md) files which define how your app and widgets will look, while keeping your Python code free of display related code (which tends to be messy).
The following chapter on [Textual CSS](CSS.md) will describe how to use CSS in detail. For now lets look at how your app references external CSS files.
The following example sets the `css_path` attribute on the app:
```python title="question02.py" hl_lines="15"
--8<-- "docs/examples/app/question02.py"
```
If the path is relative (as it is above) then it is taken as relative to where the app is defined. Hence this example references `"question01.css"` in the same directory as the Python code. Here is that CSS file:
```sass title="question02.css"
--8<-- "docs/examples/app/question02.css"
```
When `"question02.py"` runs it will load `"question02.css"` and update the app and widgets accordingly. Even though the code is almost identical to the previous sample, the app now looks quite different:
```{.textual path="docs/examples/app/question02.py"}
```
### Classvar CSS
While external CSS files are recommended for most applications, and enable some cool features like *live editing* (see below), you can also specify the CSS directly within the Python code. To do this you can set the `CSS` class variable on the app which contains the CSS content.
Here's the question app with classvar CSS:
```python title="question03.py" hl_lines="6-24"
--8<-- "docs/examples/app/question03.py"
```

View File

@@ -27,7 +27,7 @@ textual run my_app.py
The `run` sub-command assumes you have an App instance called `app` in the global scope of your Python file. If the application is called something different, you can specify it with a colon following the filename: The `run` sub-command assumes you have an App instance called `app` in the global scope of your Python file. If the application is called something different, you can specify it with a colon following the filename:
``` ```bash
textual run my_app.py:alternative_app textual run my_app.py:alternative_app
``` ```
@@ -35,9 +35,22 @@ textual run my_app.py:alternative_app
If the Python file contains a call to app.run() then you can launch the file as you normally would any other Python program. Running your app via `textual run` will give you access to a few Textual features such as live editing of CSS files. If the Python file contains a call to app.run() then you can launch the file as you normally would any other Python program. Running your app via `textual run` will give you access to a few Textual features such as live editing of CSS files.
## Live editing
If you combine the `run` command with the `--dev` switch your app will run in *development mode*.
```bash
textual run --dev my_app.py
```
One of the the features of *dev* mode is live editing of CSS files: any changes to your CSS will be reflected in the terminal a few milliseconds later.
This is a great feature for iterating on your app's look and feel. Open the CSS in your editor and have your app running in a terminal. Edits to your CSS will appear almost immediately after you save.
## Console ## Console
When running a terminal application, you will generally no longer be able to use `print` when debugging (or log to the console). This is because anything you write to standard output would overwrite application content, making it unreadable. Fortunately Textual supplies a debug console of its own which has some super helpful features. When building a typical terminal application you are generally unable to use `print` when debugging (or log to the console). This is because anything you write to standard output will overwrite application content. Textual has a solution to this in the form of a debug console which restores `print` and adds a few additional features to help you debug.
To use the console, open up **two** terminal emulators. Run the following in one of the terminals: To use the console, open up **two** terminal emulators. Run the following in one of the terminals:
@@ -58,6 +71,7 @@ textual run --dev my_app.py
Anything you `print` from your application will be displayed in the console window. Textual will also write log messages to this window which may be helpful when debugging your application. Anything you `print` from your application will be displayed in the console window. Textual will also write log messages to this window which may be helpful when debugging your application.
### Verbosity ### Verbosity
Textual writes log messages to inform you about certain events, such as when the user presses a key or clicks on the terminal. To avoid swamping you with too much information, some events are marked as "verbose" and will be excluded from the logs. If you want to see these log messages, you can add the `-v` switch. Textual writes log messages to inform you about certain events, such as when the user presses a key or clicks on the terminal. To avoid swamping you with too much information, some events are marked as "verbose" and will be excluded from the logs. If you want to see these log messages, you can add the `-v` switch.
@@ -91,7 +105,7 @@ log("[bold red]DANGER![/] We're having too much fun")
### Log method ### Log method
There's a convenient shortcut to `log` available on the App and Widget objects you can use in event handlers: There's a convenient shortcut to `log` available on the App and Widget objects. This is useful in event handlers. Here's an example:
```python ```python
from textual.app import App from textual.app import App

1
docs/guide/reactivity.md Normal file
View File

@@ -0,0 +1 @@
# Reactivity

1
docs/guide/screens.md Normal file
View File

@@ -0,0 +1 @@
# Screens

1
docs/guide/widgets.md Normal file
View File

@@ -0,0 +1 @@
# Widgets

View File

@@ -1,26 +1,26 @@
# Introduction # Tutorial
Welcome to the Textual Introduction! Welcome to the Textual Tutorial!
By the end of this page you should have a solid understanding of app development with Textual. By the end of this page you should have a solid understanding of app development with Textual.
!!! quote !!! quote
This page goes in to more detail than you may expect from an introduction. I like documentation to have complete working examples and I wanted the first app to be realistic. I've always thought the secret sauce in making a popular framework is for it to be fun. I hope you enjoy this tutorial!
&mdash; **Will McGugan** (creator of Rich and Textual) &mdash; **Will McGugan** (creator of Rich and Textual)
## Stopwatch Application ## Stopwatch Application
We're going to build a stopwatch application. It should show a list of stopwatches with a time display the user can start, stop, and reset. We also want the user to be able to add and remove stopwatches as required. We're going to build a stopwatch application. This application should show a list of stopwatches with a time display the user can start, stop, and reset. We also want the user to be able to add and remove stopwatches as required.
This will be a simple yet **fully featured** app &mdash; you could distribute this app if you wanted to! This will be a simple yet **fully featured** app &mdash; you could distribute this app if you wanted to!
Here's what the finished app will look like: Here's what the finished app will look like:
```{.textual path="docs/examples/introduction/stopwatch.py" press="tab,enter,_,tab,enter,_,tab,_,enter,_,tab,enter,_,_"} ```{.textual path="docs/examples/tutorial/stopwatch.py" press="tab,enter,_,tab,enter,_,tab,_,enter,_,tab,enter,_,_"}
``` ```
### Get the code ### Get the code
@@ -45,10 +45,10 @@ If you want to try the finished Stopwatch app and follow along with the code, fi
gh repo clone Textualize/textual gh repo clone Textualize/textual
``` ```
With the repository cloned, navigate to `docs/examples/introduction` and run `stopwatch.py`. With the repository cloned, navigate to `docs/examples/tutorial` and run `stopwatch.py`.
```bash ```bash
cd textual/docs/examples/introduction cd textual/docs/examples/tutorial
python stopwatch.py python stopwatch.py
``` ```
@@ -58,7 +58,7 @@ python stopwatch.py
Type hints are entirely optional in Textual. We've included them in the example code but it's up to you whether you add them to your own projects. Type hints are entirely optional in Textual. We've included them in the example code but it's up to you whether you add them to your own projects.
We're a big fan of Python type hints at Textualize. If you haven't encountered type hinting, it's a way to express the types of your data, parameters, and return values. Type hinting allows tools like [Mypy](https://mypy.readthedocs.io/en/stable/) to catch potential bugs before your code runs. We're a big fan of Python type hints at Textualize. If you haven't encountered type hinting, it's a way to express the types of your data, parameters, and return values. Type hinting allows tools like [Mypy](https://mypy.readthedocs.io/en/stable/) to catch bugs before your code runs.
The following function contains type hints: The following function contains type hints:
@@ -77,18 +77,18 @@ def repeat(text: str, count: int) -> str:
The first step in building a Textual app is to import and extend the `App` class. Here's our basic app class with a few methods we will cover below. The first step in building a Textual app is to import and extend the `App` class. Here's our basic app class with a few methods we will cover below.
```python title="stopwatch01.py" ```python title="stopwatch01.py"
--8<-- "docs/examples/introduction/stopwatch01.py" --8<-- "docs/examples/tutorial/stopwatch01.py"
``` ```
If you run this code, you should see something like the following: If you run this code, you should see something like the following:
```{.textual path="docs/examples/introduction/stopwatch01.py"} ```{.textual path="docs/examples/tutorial/stopwatch01.py"}
``` ```
Hit the ++d++ key to toggle dark mode. Hit the ++d++ key to toggle dark mode.
```{.textual path="docs/examples/introduction/stopwatch01.py" press="d" title="TimerApp + dark"} ```{.textual path="docs/examples/tutorial/stopwatch01.py" press="d" title="TimerApp + dark"}
``` ```
Hit ++ctrl+c++ to exit the app and return to the command prompt. Hit ++ctrl+c++ to exit the app and return to the command prompt.
@@ -98,27 +98,27 @@ Hit ++ctrl+c++ to exit the app and return to the command prompt.
Let's examine stopwatch01.py in more detail. Let's examine stopwatch01.py in more detail.
```python title="stopwatch01.py" hl_lines="1 2" ```python title="stopwatch01.py" hl_lines="1 2"
--8<-- "docs/examples/introduction/stopwatch01.py" --8<-- "docs/examples/tutorial/stopwatch01.py"
``` ```
The first line imports the Textual `App` class. The second line imports two builtin widgets: `Footer` which shows available keys and `Header` which shows a title and the current time. The first line imports the Textual `App` class. The second line imports two builtin widgets: `Footer` which shows available keys and `Header` which shows a title and the current time.
Widgets are re-usable components responsible for managing a part of the screen. We will cover how to build such widgets in this introduction. Widgets are re-usable components responsible for managing a part of the screen. We will cover how to build such widgets in this tutorial.
```python title="stopwatch01.py" hl_lines="5-19" ```python title="stopwatch01.py" hl_lines="5-19"
--8<-- "docs/examples/introduction/stopwatch01.py" --8<-- "docs/examples/tutorial/stopwatch01.py"
``` ```
The App class is where most of the logic of Textual apps is written. It is responsible for loading configuration, setting up widgets, handling keys, and more. The App class is where most of the logic of Textual apps is written. It is responsible for loading configuration, setting up widgets, handling keys, and more.
Currently, there are three methods in our stopwatch app. Currently, there are three methods in our stopwatch app.
- **`compose()`** is where we construct a user interface with widgets. The `compose()` method may return a list of widgets, but it is generally easier to _yield_ them (making this method a generator). In the example code we yield instances of the widget classes we imported, i.e. the header and the footer. - `compose()` is where we construct a user interface with widgets. The `compose()` method may return a list of widgets, but it is generally easier to _yield_ them (making this method a generator). In the example code we yield instances of the widget classes we imported, i.e. the header and the footer.
- **`on_load()`** is an _event handler_ method. Event handlers are called by Textual in response to external events like keys and mouse movements, and internal events needed to manage your application. Event handler methods begin with `on_` followed by the name of the event (in lower case). Hence, `on_load` is called in response to the Load event which is sent just after the app starts. We're using this event to call `App.bind()` which connects a key to an _action_. - `on_load()` is an _event handler_ method. Event handlers are called by Textual in response to external events like keys and mouse movements, and internal events needed to manage your application. Event handler methods begin with `on_` followed by the name of the event (in lower case). Hence, `on_load` is called in response to the Load event which is sent just after the app starts. We're using this event to call `App.bind()` which connects a key to an _action_.
- **`action_toggle_dark()`** defines an _action_ method. Actions are methods beginning with `action_` followed by the name of the action. The call to `bind()` in `on_load()` binds this the ++d++ key to this action. The body of this method flips the state of the `dark` Boolean to toggle dark mode. - `action_toggle_dark()` defines an _action_ method. Actions are methods beginning with `action_` followed by the name of the action. The call to `bind()` in `on_load()` binds this the ++d++ key to this action. The body of this method flips the state of the `dark` Boolean to toggle dark mode.
!!! note !!! note
@@ -126,7 +126,7 @@ Currently, there are three methods in our stopwatch app.
```python title="stopwatch01.py" hl_lines="22-24" ```python title="stopwatch01.py" hl_lines="22-24"
--8<-- "docs/examples/introduction/stopwatch01.py" --8<-- "docs/examples/tutorial/stopwatch01.py"
``` ```
The last few lines create an instance of the app at the module scope. Followed by a call to `run()` within a `__name__ == "__main__"` block. This is so that we could import `app` if we want to. Or we could run it with `python stopwatch01.py`. The last few lines create an instance of the app at the module scope. Followed by a call to `run()` within a `__name__ == "__main__"` block. This is so that we could import `app` if we want to. Or we could run it with `python stopwatch01.py`.
@@ -153,7 +153,7 @@ Textual has a builtin `Button` widget which takes care of the first three compon
Let's add those to the app. Just a skeleton for now, we will add the rest of the features as we go. Let's add those to the app. Just a skeleton for now, we will add the rest of the features as we go.
```python title="stopwatch02.py" hl_lines="3 6-7 10-18 28" ```python title="stopwatch02.py" hl_lines="3 6-7 10-18 28"
--8<-- "docs/examples/introduction/stopwatch02.py" --8<-- "docs/examples/tutorial/stopwatch02.py"
``` ```
### Extending widget classes ### Extending widget classes
@@ -180,7 +180,7 @@ The new line in `Stopwatch.compose()` yields a single `Container` object which w
Let's see what happens when we run "stopwatch02.py". Let's see what happens when we run "stopwatch02.py".
```{.textual path="docs/examples/introduction/stopwatch02.py" title="stopwatch02.py"} ```{.textual path="docs/examples/tutorial/stopwatch02.py" title="stopwatch02.py"}
``` ```
The elements of the stopwatch application are there. The buttons are clickable and you can scroll the container but it doesn't look like the sketch. This is because we have yet to apply any _styles_ to our new widgets. The elements of the stopwatch application are there. The buttons are clickable and you can scroll the container but it doesn't look like the sketch. This is because we have yet to apply any _styles_ to our new widgets.
@@ -204,18 +204,18 @@ While it's possible to set all styles for an app this way, it is rarely necessar
Let's add a CSS file to our application. Let's add a CSS file to our application.
```python title="stopwatch03.py" hl_lines="39" ```python title="stopwatch03.py" hl_lines="39"
--8<-- "docs/examples/introduction/stopwatch03.py" --8<-- "docs/examples/tutorial/stopwatch03.py"
``` ```
Adding the `css_path` attribute to the app constructor tells Textual to load the following file when it starts the app: Adding the `css_path` attribute to the app constructor tells Textual to load the following file when it starts the app:
```sass title="stopwatch03.css" ```sass title="stopwatch03.css"
--8<-- "docs/examples/introduction/stopwatch03.css" --8<-- "docs/examples/tutorial/stopwatch03.css"
``` ```
If we run the app now, it will look *very* different. If we run the app now, it will look *very* different.
```{.textual path="docs/examples/introduction/stopwatch03.py" title="stopwatch03.py"} ```{.textual path="docs/examples/tutorial/stopwatch03.py" title="stopwatch03.py"}
``` ```
This app looks much more like our sketch. Textual has read style information from `stopwatch03.css` and applied it to the widgets. This app looks much more like our sketch. Textual has read style information from `stopwatch03.css` and applied it to the widgets.
@@ -295,7 +295,7 @@ We can accomplish this with a CSS _class_. Not to be confused with a Python clas
Here's the new CSS: Here's the new CSS:
```sass title="stopwatch04.css" hl_lines="33-53" ```sass title="stopwatch04.css" hl_lines="33-53"
--8<-- "docs/examples/introduction/stopwatch04.css" --8<-- "docs/examples/tutorial/stopwatch04.css"
``` ```
These new rules are prefixed with `.started`. The `.` indicates that `.started` refers to a CSS class called "started". The new styles will be applied only to widgets that have this CSS class. These new rules are prefixed with `.started`. The `.` indicates that `.started` refers to a CSS class called "started". The new styles will be applied only to widgets that have this CSS class.
@@ -323,14 +323,14 @@ You can add and remove CSS classes with the `add_class()` and `remove_class()` m
The following code adds an event handler for the `Button.Pressed` event. The following code adds an event handler for the `Button.Pressed` event.
```python title="stopwatch04.py" hl_lines="13-18" ```python title="stopwatch04.py" hl_lines="13-18"
--8<-- "docs/examples/introduction/stopwatch04.py" --8<-- "docs/examples/tutorial/stopwatch04.py"
``` ```
The `on_button_pressed` event handler is called when the user clicks a button. This method adds the "started" class when the "start" button was clicked, and removes the class when the "stop" button is clicked. The `on_button_pressed` event handler is called when the user clicks a button. This method adds the "started" class when the "start" button was clicked, and removes the class when the "stop" button is clicked.
If you run "stopwatch04.py" now you will be able to toggle between the two states by clicking the first button: If you run "stopwatch04.py" now you will be able to toggle between the two states by clicking the first button:
```{.textual path="docs/examples/introduction/stopwatch04.py" title="stopwatch04.py" press="tab,tab,tab,enter"} ```{.textual path="docs/examples/tutorial/stopwatch04.py" title="stopwatch04.py" press="tab,tab,tab,enter"}
``` ```
## Reactive attributes ## Reactive attributes
@@ -340,7 +340,7 @@ A recurring theme in Textual is that you rarely need to explicitly update a widg
You can declare a reactive attribute with `textual.reactive.Reactive`. Let's use this feature to create a timer that displays elapsed time and keeps it updated. You can declare a reactive attribute with `textual.reactive.Reactive`. Let's use this feature to create a timer that displays elapsed time and keeps it updated.
```python title="stopwatch04.py" hl_lines="1 5 12-27" ```python title="stopwatch04.py" hl_lines="1 5 12-27"
--8<-- "docs/examples/introduction/stopwatch05.py" --8<-- "docs/examples/tutorial/stopwatch05.py"
``` ```
We have added two reactive attributes: `start_time` will contain the time in seconds when the stopwatch was started, and `time` will contain the time to be displayed on the Stopwatch. We have added two reactive attributes: `start_time` will contain the time in seconds when the stopwatch was started, and `time` will contain the time to be displayed on the Stopwatch.
@@ -368,7 +368,7 @@ Because `watch_time` watches the `time` attribute, when we update `self.time` 60
The end result is that the `Stopwatch` widgets show the time elapsed since the widget was created: The end result is that the `Stopwatch` widgets show the time elapsed since the widget was created:
```{.textual path="docs/examples/introduction/stopwatch05.py" title="stopwatch05.py"} ```{.textual path="docs/examples/tutorial/stopwatch05.py" title="stopwatch05.py"}
``` ```
We've seen how we can update widgets with a timer, but we still need to wire up the buttons so we can operate Stopwatches independently. We've seen how we can update widgets with a timer, but we still need to wire up the buttons so we can operate Stopwatches independently.
@@ -379,7 +379,7 @@ We need to be able to start, stop, and reset each stopwatch independently. We ca
```python title="stopwatch06.py" hl_lines="14-44 50-61" ```python title="stopwatch06.py" hl_lines="14-44 50-61"
--8<-- "docs/examples/introduction/stopwatch06.py" --8<-- "docs/examples/tutorial/stopwatch06.py"
``` ```
Here's a summary of the changes made to `TimeDisplay`. Here's a summary of the changes made to `TimeDisplay`.
@@ -415,7 +415,7 @@ This code supplies missing features and makes our app useful. We've made the fol
If you run stopwatch06.py you will be able to use the stopwatches independently. If you run stopwatch06.py you will be able to use the stopwatches independently.
```{.textual path="docs/examples/introduction/stopwatch06.py" title="stopwatch06.py" press="tab,enter,_,_,tab,enter,_,tab"} ```{.textual path="docs/examples/tutorial/stopwatch06.py" title="stopwatch06.py" press="tab,enter,_,_,tab,enter,_,tab"}
``` ```
The only remaining feature of the Stopwatch app left to implement is the ability to add and remove timers. The only remaining feature of the Stopwatch app left to implement is the ability to add and remove timers.
@@ -429,7 +429,7 @@ To add a new child widget call `mount()` on the parent. To remove a widget, call
Let's use these to implement adding and removing stopwatches to our app. Let's use these to implement adding and removing stopwatches to our app.
```python title="stopwatch.py" hl_lines="83-84 86-90 92-96" ```python title="stopwatch.py" hl_lines="83-84 86-90 92-96"
--8<-- "docs/examples/introduction/stopwatch.py" --8<-- "docs/examples/tutorial/stopwatch.py"
``` ```
We've added two new actions: `action_add_stopwatch` to add a new stopwatch, and `action_remove_stopwatch` to remove the last stopwatch. The `on_load` handler binds these actions to the ++a++ and ++r++ keys. We've added two new actions: `action_add_stopwatch` to add a new stopwatch, and `action_remove_stopwatch` to remove the last stopwatch. The `on_load` handler binds these actions to the ++a++ and ++r++ keys.
@@ -440,11 +440,11 @@ The `action_remove_stopwatch` calls `query` with a CSS selector of `"Stopwatch"`
If you run `stopwatch.py` now you can add a new stopwatch with the ++a++ key and remove a stopwatch with ++r++. If you run `stopwatch.py` now you can add a new stopwatch with the ++a++ key and remove a stopwatch with ++r++.
```{.textual path="docs/examples/introduction/stopwatch.py" press="d,a,a,a,a,a,a,a,tab,enter,_,_,_,_,tab,_"} ```{.textual path="docs/examples/tutorial/stopwatch.py" press="d,a,a,a,a,a,a,a,tab,enter,_,_,_,_,tab,_"}
``` ```
## What next? ## What next?
Congratulations on building your first Textual application! This introduction has covered a lot of ground. If you are the type that prefers to learn a framework by coding, feel free. You could tweak stopwatch.py or look through the examples. Congratulations on building your first Textual application! This tutorial has covered a lot of ground. If you are the type that prefers to learn a framework by coding, feel free. You could tweak stopwatch.py or look through the examples.
Read the guide for the full details on how to build sophisticated TUI applications with Textual. Read the guide for the full details on how to build sophisticated TUI applications with Textual.

View File

@@ -4,13 +4,17 @@ site_url: https://www.textualize.io/
nav: nav:
- "index.md" - "index.md"
- "getting_started.md" - "getting_started.md"
- "introduction.md" - "tutorial.md"
- Guide: - Guide:
- "guide/app.md"
- "guide/devtools.md" - "guide/devtools.md"
- "guide/layout.md" - "guide/app.md"
- "guide/CSS.md" - "guide/CSS.md"
- "guide/layout.md"
- "guide/events.md" - "guide/events.md"
- "guide/actions.md"
- "guide/reactivity.md"
- "guide/widgets.md"
- "guide/screens.md"
- How to: - How to:
- "how-to/animation.md" - "how-to/animation.md"
- "how-to/mouse-and-keyboard.md" - "how-to/mouse-and-keyboard.md"

View File

@@ -45,7 +45,8 @@ class Button(Widget, can_focus=True):
} }
Button.-disabled { Button.-disabled {
opacity: 0.6; opacity: 0.4;
text-opacity: 0.7;
} }
Button:focus { Button:focus {
@@ -84,7 +85,6 @@ class Button(Widget, can_focus=True):
background: $primary; background: $primary;
border-bottom: tall $primary-lighten-3; border-bottom: tall $primary-lighten-3;
border-top: tall $primary-darken-3; border-top: tall $primary-darken-3;
} }
@@ -94,13 +94,11 @@ class Button(Widget, can_focus=True):
color: $text-success; color: $text-success;
border-top: tall $success-lighten-2; border-top: tall $success-lighten-2;
border-bottom: tall $success-darken-3; border-bottom: tall $success-darken-3;
} }
Button.-success:hover { Button.-success:hover {
background: $success-darken-2; background: $success-darken-2;
color: $text-success-darken-2; color: $text-success-darken-2;
} }
Button.-success.-active { Button.-success.-active {
@@ -199,6 +197,11 @@ class Button(Widget, can_focus=True):
variant = Reactive.init("default") variant = Reactive.init("default")
disabled = Reactive(False) disabled = Reactive(False)
def watch_mouse_over(self, value: bool) -> None:
"""Update from CSS if mouse over state changes."""
if not self.disabled:
self.app.update_styles(self)
def validate_variant(self, variant: str) -> str: def validate_variant(self, variant: str) -> str:
if variant not in _VALID_BUTTON_VARIANTS: if variant not in _VALID_BUTTON_VARIANTS:
raise InvalidButtonVariant( raise InvalidButtonVariant(