如何使用Kivy获取TextInput的值

4
我是Kivy的新手,因为我无法在PySide上进行实践(一些动态库损坏或我不知道什么原因),所以我想尝试一下这个巨大的工具。
我现在很迷茫,尝试着像这样做: 获取Kivy应用程序中的TextInput值 但是我没有按照相同的方式去做:
<ProduitScreen>:
    GridLayout:
        rows: 3
        cols: 2
        padding: 10
        spacing: 10
        Label:
            font_size: 20
            text: 'Nom du produit'
        TextInput:
            font_size: 20
            id: nom
        Label:
            font_size: 20
            text: 'Prix'
        TextInput:
            font_size: 20
            id: prix
        Button:
            text: 'Ajouter'
            on_press: self.ajouter()
        Button:
            text: 'Quitter'
            on_press: root.manager.current = 'menu'

因此,填充有“添加”文本字段的按钮必须允许我获取两个字段的值并将它们添加到列表中,但是:
AttributeError: 'Button' object has no attribute 'ajouter'

在我的课堂中,它被定义为:

class ProduitScreen(Screen):
    def ajouter():
        print "%s au prix de %d a ete ajoute" % (self.nom.txt , float(self.prix.txt))

有人能告诉我如何做吗?

编辑:黑色引用不会保存缩进,这是完整代码http://pastebin.com/W1WJ8NcL

1个回答

3

ajouter 方法是 ProduitScreen 的成员,而不是 Button,因此您应该使用 root 来引用它:

    Button:
        text: 'Ajouter'
        on_press: root.ajouter()

同时修复有关ajouter定义的问题:

class ProduitScreen(Screen):
    def ajouter(self):
        print "%s au prix de %f a ete ajoute" % (self.nom.text , float(self.prix.text))

为了在Python代码中使用nomprix,请将以下代码添加到kv代码中:
<ProduitScreen>:
    nom: nom
    prix: prix

它绝对有效! 我可以调用哪个函数来退出应用程序?(适用于Android、Unix、Windows等的通用函数...) - Jérémy JOKE
1
尝试 from kivy.app import App; App.get_running_app().stop() - Assem
太棒了。如果我在使用Kivy时遇到麻烦,我会和你交流一下。非常感谢你,伙计。 - Jérémy JOKE
一个问题。现在我知道如何从GUI中获取数据,但如何将数据用于GUI呢?我有一个列表,想要从中生成按钮和标签。怎么做?^^ - Jérémy JOKE
如果您觉得解释很长,我建议您将其作为新问题提出,我很乐意回答,也会有其他用户帮助回答。 - Assem
好的,我会的。待会儿见。 - Jérémy JOKE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接