diff --git a/docs/examples/guide/compound/byte02.py b/docs/examples/guide/compound/byte02.py index 865287a3bc..f0249ad02d 100644 --- a/docs/examples/guide/compound/byte02.py +++ b/docs/examples/guide/compound/byte02.py @@ -31,7 +31,7 @@ def __init__(self, bit: int, value: bool) -> None: self.bit = bit self.value = value - value = reactive(0) # (1)! + value = reactive(False) # (1)! def __init__(self, bit: int) -> None: self.bit = bit @@ -90,9 +90,12 @@ def compose(self) -> ComposeResult: def on_bit_switch_bit_changed(self, event: BitSwitch.BitChanged) -> None: """When a switch changes, update the value.""" - value = 0 - for switch in self.query(BitSwitch): - value |= switch.value << switch.bit + current_value = int(self.query_one(Input).value or "0") + value_change = 1 << event.bit + if event.value: # Bit changed from 0 to 1. + value = current_value + value_change + else: # Bit changed from 1 to 0. + value = current_value - value_change self.query_one(Input).value = str(value) diff --git a/docs/examples/guide/compound/byte03.py b/docs/examples/guide/compound/byte03.py index 3988ea467f..a0f032a972 100644 --- a/docs/examples/guide/compound/byte03.py +++ b/docs/examples/guide/compound/byte03.py @@ -32,7 +32,7 @@ def __init__(self, bit: int, value: bool) -> None: self.bit = bit self.value = value - value = reactive(0) + value = reactive(False) def __init__(self, bit: int) -> None: self.bit = bit @@ -101,9 +101,12 @@ def compose(self) -> ComposeResult: def on_bit_switch_bit_changed(self, event: BitSwitch.BitChanged) -> None: """When a switch changes, update the value.""" - value = 0 - for switch in self.query(BitSwitch): - value |= switch.value << switch.bit + current_value = int(self.query_one(Input).value or "0") + value_change = 1 << event.bit + if event.value: # Bit changed from 0 to 1. + value = current_value + value_change + else: # Bit changed from 1 to 0. + value = current_value - value_change self.query_one(Input).value = str(value) def on_input_changed(self, event: Input.Changed) -> None: # (3)! diff --git a/docs/guide/widgets.md b/docs/guide/widgets.md index d8c9e85f6d..9253e84fd4 100644 --- a/docs/guide/widgets.md +++ b/docs/guide/widgets.md @@ -655,7 +655,7 @@ Let's extend the `ByteEditor` so that clicking any of the 8 `BitSwitch` widgets === "byte02.py" - ```python title="byte02.py" hl_lines="5-6 26-32 34 44-48 91-96" + ```python title="byte02.py" hl_lines="5-6 26-32 34 44-48 91-99" --8<-- "docs/examples/guide/compound/byte02.py" ``` @@ -688,7 +688,7 @@ This is an example of "attributes down". === "byte03.py" - ```python title="byte03.py" hl_lines="5 45-47 90 92-94 109-114 116-120" + ```python title="byte03.py" hl_lines="5 45-47 90 92-94 112-117 119-123" --8<-- "docs/examples/guide/compound/byte03.py" ```