You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Textual天气应用:如何正确获取Input组件输入值

解决Textual Input组件值获取问题

核心问题分析

你看到的内存地址输出,说明getLocation方法返回的是Location类的实例对象,而非你期望的字符串值。大概率是方法逻辑错误,比如误将self作为返回值,或是未正确返回处理后的字符串。

修正步骤

1. 修正Location类的getLocation方法

确保方法根据输入值返回正确的字符串:

class Location:
    def getLocation(self, input_value):
        # 输入为空时返回"Test",否则返回输入值
        if not input_value.strip():
            return "Test"
        else:
            return input_value

2. 正确获取Textual Input组件的值

在Textual应用中,要在合适的时机(比如按钮点击事件)获取Input的值,而非组件初始化阶段:

from textual.app import App, ComposeResult
from textual.widgets import Input, Button, Label

class WeatherApp(App):
    def compose(self) -> ComposeResult:
        yield Input(placeholder="输入城市/州/国家")
        yield Button("查询")
        yield Label(id="result")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        # 获取Input组件实例
        input_widget = self.query_one(Input)
        # 获取输入值
        input_value = input_widget.value
        # 调用Location类方法并获取结果
        location = Location()
        result = location.getLocation(input_value)
        # 更新页面显示结果
        self.query_one("#result", Label).update(result)

if __name__ == "__main__":
    WeatherApp().run()

3. 常见错误排查

  • 不要直接打印Location实例:如果写成print(location),会输出对象内存地址,需打印方法的返回值print(result)。
  • 确保Input组件引用正确:用query_one(Input)获取页面上的实际组件,而非创建新的未绑定的Input实例。

内容的提问来源于stack exchange,提问作者Austin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 12:27:07