python - 如何使用 Kivy 获取 textinput 的值

标签 python python-2.7 kivy

我是 Kivy 的新手,因为我无法在 PySide 上练习(一些动态库坏了或者我不知道是什么)我想尝试这个巨大的工具。

我现在迷路了,我试着这样做: Get textinput value in Kivy app

但我不会以同样的方式这样做:

<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'

因此,字段文本填充为“Ajouter”的按钮必须允许我获取两个字段的值并将它们添加到列表中,但是:

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))

有人可以告诉我该怎么做吗?

编辑:blackquote 不保存缩进,所以有完整的代码 http://pastebin.com/W1WJ8NcL

最佳答案

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

关于python - 如何使用 Kivy 获取 textinput 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084664/

相关文章:

Python 正则表达式 sub 单个字符

python - Python 3 中未调用覆盖的 TreeCtrl.OnCompareItems() - wxPython 4

python - Kivy:使用 on_press 事件在屏幕管理器中更改屏幕

python - 为什么 os.path.dirname(__file__) 在 Django 中有效?

python - 如果默认 python 是 python3,则安装 python2 模块

eclipse - Kivy、Eclipse 和 PyDev(也是 PyPy)

python - Kivy 毫不拖延地捕获触摸

python - 如何通过 API 使用 For 循环从 Google Drive 下载文件

python - 用 pandas 组合多个列

python - 在 Numpy 中运行 max/limsup : what optimization?