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

Kivy框架TextInput内容无法提取至Python变量问题求助

解决Kivy TextInput无法获取输入内容的问题

你的代码存在几个关键错误,导致无法正常提取TextInput的输入内容,以下是具体修正方案:

错误点及修正说明

  • 类方法缺少self参数:get_text方法未传入self,这是Python类实例方法的必需参数,没有它无法访问类内部的属性和组件。
  • Kv文件中id格式错误:TextInput的id: 'text_id'多了引号,Kv语言中id不需要加引号,正确写法是id: text_id。
  • 组件获取方式错误:应该通过self.ids.text_id获取TextInput组件,而非self.root.text_id——self.root指向应用根部件,这里MainWidget本身就是根部件,直接用self.ids访问内部组件即可。
  • 缺少App类导入:代码中from kivy.app import App被注释,必须导入该模块才能运行App类。

修正后的Python代码

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput

class MainWidget(Widget):  
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def get_text(self):    # 添加self参数
        text = self.ids.text_id.text  # 正确通过self.ids获取组件
        print("输入内容:", text)
        print("it work")

    def test(self):
        print("it work")
    
class Counter_app(BoxLayout):
    count_var = 0
    text = StringProperty("0")

    def count_click(self):
        self.count_var += 1 
        self.text = str(self.count_var)

class appliApp(App):
    def build(self):
        return MainWidget()

appliApp().run()

修正后的Kv文件代码

<Counter_app>:
    Button:
        background_color: "blue"
        text: "count"
        on_press: root.count_click()
               
    Label:
        text: root.text
        color: "green"
        font_size: "50"
        canvas.before:
            Rectangle:
                pos: self.pos
                size: self.size
                source: 'images/img2.jpg'

<font@BoxLayout>: 
    Image:
        source: "images/img2.jpg"
        size: 500,500
    Label:
        background_image: "images/img6"
        background_color: "green"
       
<MainWidget>:
    canvas.before:
        Rectangle:
            pos: self.pos
            size: self.size
            source: 'img3.png'

    Button:
        pos: 300, 100 
        text: "get text"
        on_press: root.get_text()

    TextInput:
        id: text_id  # 去掉引号
        hint_text: "Enter your name"

修改完成后,点击"get text"按钮即可正确获取并打印TextInput中的输入内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:17:19