Calculation of the number of symbols in TextInput



  • If I enter the textInput numbers and then they are immediately or removed, then textInput does not become an empty line and does not show the number of symbols equal to 0.

    How, when the last symbol (or all at once) is removed, is the length of the line 0?

    from kivy.app import App
    from kivy.uix.textinput import TextInput
    from kivy.uix.label import Label
    from kivy.uix.boxlayout import BoxLayout
    

    class MainApp(App):
    def build(self):
    bl = BoxLayout(orientation = 'vertical')
    self.txt = TextInput()
    self.txt.bind(text=self.on_focusa)
    bl.add_widget(self.txt)
    self.lab = Label()
    bl.add_widget(self.lab)

        return bl
    
    def on_focusa(self, instance, value):
        try:
            txt = int(self.txt.text)*2
            self.lab.text = str(txt)
            print(len(str(txt)))
        except ValueError:
            pass
    

    if name == 'main':
    MainApp().run()



  • The problem is, when you remove all the signs from the text field, the value doesn't come on_focusa, the function doesn't work as you wish.

    Such a code can solve the problem, it can be optimized if the repetitive code is placed in a separate function:

        def on_focusa(self, instance, value):
        if value: # Проверяем значение value
            try:
                txt = int(self.txt.text)*2
                self.lab.text = str(txt)
                print(len(str(txt)))
            except ValueError:
                pass
        else: # Если value отсутствует, то выводим нули
            txt = 0
            self.lab.text = str(txt)
            print(len(str(txt)))
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2