简体   繁体   中英

Kivy: How to correctly manipulate a widget in python that is defined in KV lang

I have have the following that's written in KV lang:

    TextInput:
        id: user_input_temp
        font_size: 50
        size_hint_y: None
        input_filter: 'float'
        multiline: False

    Label:
        text: "Celsius"
    Label:
        id: celsius
        text: root.temp_conv()

And I attempt to use user_input_temp in python code:

    class Temperature(Screen,BoxLayout):

        def temp_conv(self):
            number = self.ids.user_input_temp.text
            input =  float(number)
            celsius = (input - 32)*(5/9)
            self.ids.celsius.text = str(celsius)

But I receive an error - ValueError: could not convert string to float: How can I correctly convert .text of the widget? (preferably by using the widget id)

Check what value it can't convert. In your example, you don't actually set the text so it's probably doing float('') , which would give the error that you see since '' doesn't describe a float. In that case you'd want to try to do the conversion, but return something suitable or do nothing at all if it fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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