简体   繁体   English

如何在 Kivy 中使用 NumericProperty()?

[英]How to use NumericProperty() in Kivy?

I am trying to get a value from the .kv file to the Python file as follows:我试图从 .kv 文件中获取一个值到 Python 文件,如下所示:

Python: Python:

class Calc(Widget):    
    def func(self):

        alp = NumericProperty()
        bet = NumericProperty()

        some calculation ... alp + bet

Kivy:基维:

<Calc>

 alp: alpha.text
 bet: beta.text

 TextInput:
     id: alpha
 TextInput:
     id: beta

I have tried different things (eg converting the string to float, int, etc) nothing seems to work.我尝试了不同的事情(例如将字符串转换为浮点数、整数等)似乎没有任何效果。 I tried using "alp: alpha", and that does not seem to work either.我尝试使用“alp:alpha”,但这似乎也不起作用。

What am I doing wrong?我究竟做错了什么?

Thank you!谢谢!


Revision 1修订版 1

Python: Python:

class Calc(Widget):    

    alp = NumericProperty()
    bet = NumericProperty()

    def func(self):

        some calculation ... alp + bet

Kivy:基维:

<Calc>

    alp: alpha.text
    bet: beta.text

    TextInput:
        id: alpha
    TextInput:
        id: beta

So, it is still not working - because eg alpha.text returns a string to alp = NumericProperty().因此,它仍然无法正常工作 - 因为例如 alpha.text 将字符串返回给 alp = NumericProperty()。 As far as I know, ".text" is the only attribute that returns the content of the InputLabel.据我所知,“.text”是唯一返回 InputLabel 内容的属性。 Any ideas?有任何想法吗? Thank you.谢谢你。


Revision 2修订版 2

It seems like I have solved the problem by using ObjectProperty().似乎我已经通过使用 ObjectProperty() 解决了这个问题。

Python: Python:

class Calc(Widget):    
def func(self):

    alp = ObjectProperty('float')
    bet = ObjectProperty('float')

    some calculation ... alp + bet

I also applied the filters 'float' but I do not think they are doing anything.我还应用了过滤器“浮动”,但我认为他们没有做任何事情。 Does anyone know how to set up a nice Error Handler if the user inputs other than numeric values?如果用户输入的不是数值,有谁知道如何设置一个好的错误处理程序?

Kivy properties must be declared at the class level. Kivy 属性必须在类级别声明。 Check out this part of the tutorial: http://kivy.org/docs/gettingstarted/properties.html查看教程的这一部分: http : //kivy.org/docs/gettingstarted/properties.html

That means you should have something like这意味着你应该有类似的东西

class Calc(Widget):

    alp = NumericProperty()
    bet = NumericProperty()

    def func(self):
        some calculation ... alp + bet

if your aim is to get input from Text_Input access text attribute and cast them to float or int and add them and display the result, below code should help如果您的目标是从 Text_Input 访问文本属性获取输入并将它们转换为 float 或 int 并添加它们并显示结果,下面的代码应该会有所帮助

class Calc(Widget):    
   alp = ObjectProperty()
   bet = ObjectProperty()

   def func(self):          
      #some calculation ... alp + bet
      add = float(self.alp.text)+ float(self.bet.text)
      #print add to cmd prompt
      print(add)

this might help :)这可能会有所帮助:)

用这个:

from kivy.properties import *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM