从类的.kv文件中定义的TextInput获取文本

2024-06-16 11:42:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了以下代码:

from kivy.app import App
from kivy.uix.widget import Widget
class UI(Widget):
    pass

class UIApp(App):
    def build(self):
        return UI()

    def process(self):
        text = self.ids.input.text
        print(text)

在千伏公司名称:

^{pr2}$

现在如果我调用process(),我会得到错误'UIApp' object has no attribute 'ids'。好吧。现在我尝试用UI:AttributeError: 'kivy.properties.DictProperty' object has no attribute 'input'替换self。尝试访问'test1'也没有帮助,删除.kv文件中的'around the id'也没有帮助。在

有没有一种方法可以在不编程的情况下从字段中获取输入?在


Tags: textfromimportselfappidsuiinput
1条回答
网友
1楼 · 发布于 2024-06-16 11:42:26

问题

在kv文件中,您已经将id定义为字符串。

Kivy » Referencing Widgets

Warning

When assigning a value to id, remember that the value isn’t a string. There are no quotes: good -> id: value, bad -> id: 'value'

解决方案

  1. 在kv文件中,删除所有id中的单引号
  2. 在Python脚本中,将self.ids.input.text替换为self.root.ids.input.text,因为ids是在根class UI()下定义的

示例

kv文件

#:kivy 1.0.9

<UI>:
    title: 'InputDialog'
    auto_dismiss: False
    id: test1

    RelativeLayout:
        orientation: 'vertical'
        pos: self.pos
        size: root.size
        id: test2

        TextInput:
            id: input
            hint_text:'Enter compounds'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.95, 0.5
            on_text: app.process()

在主.py在

^{pr2}$

输出

Accesing textinput in kv file using ids

相关问题 更多 >