看起来
@click=action
在文本中不起作用(至少我根本无法使其起作用)。
在挖掘了丰富的文档之后,我开始学习Text类。那个,有
on method
,可以创建
click
回调。
它支持
__add__
,所以您可以连接多个
Text
(s) 与
+
操作人员
难题的第二部分是找出要设置的
点击
回调。我再次查看源代码,发现
_action_targets
在app.py中。它包含
{"app", "view"}
设置
将所有内容放在一起,您可以使用
文本
具有
on(click="app.callback()")
,将调用
action_callback
MyApp类的方法(文本应用程序的实例)。然后通过插入其他
文本
(s) 和链接在一起。
下面是一个工作示例,点击Hello将背景变成红色,或者点击World将背景变成绿色。
from rich.panel import Panel
from rich.text import Text
from textual.app import App
from textual.widgets import Header, Footer, ScrollView
class MyApp(App):
async def on_load(self) -> None:
await self.bind("b", "color('blue')")
async def on_mount(self) -> None:
await self.view.dock(Header(), size=5, edge="top")
await self.view.dock(Footer(), edge="bottom")
link1 = Text("Hello").on(click="app.hello()")
link2 = Text("World").on(click="app.world()")
panel_text = link1 + " " + link2 + Text(" more info here")
await self.view.dock(ScrollView(Panel(panel_text)), edge="top")
async def action_color(self, color: str) -> None:
self.app.sub_title = "KEYBOARD"
self.background = f"on {color}"
async def action_hello(self) -> None:
self.app.sub_title = "CLICKED Hello"
self.background = "on red"
async def action_world(self) -> None:
self.app.sub_title = "CLICKED World"
self.background = "on green"
MyApp.run(title="Test click", log="textual.log")
我知道这不是一个理想的解决方案,但这是我能得到的最接近你想要的。