Kivy >> On Press method triggered twice

Viewed 343

For some reason the On Press event for the instance of Word_button is being triggered twice. The code below demonstrates this.

To repeat the problem.

  • run the code below
  • click on the "CREATE LIST OF WORD" button. This create a list of buttons. Each button has Boolean property if the word is correct or not.
  • then click on the word buttons. When clicking the button, the print statements print the correct boolean variable and the text of the button.

Problem:

  • The print commands are run twice.
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen
from kivy.properties import (NumericProperty, BooleanProperty)
from kivymd.app import MDApp
from kivymd.uix.button import MDRaisedButton
from kivymd.uix.boxlayout import MDBoxLayout

kv = '''
<Word_button@MDRaisedButton>:
    pos_hint: {'center_x': .5}
    size_hint: 1, 1
    font_size: "16sp"
    on_press: self.check_word()

<Words_Box@MDBoxLayout>:
    pos_hint: {'center_x': .5}
    size_hint: 1, 1

Screen:
    id: spelling_screen
    name: "spelling_screen"
    MDBoxLayout:
        orientation: 'vertical'
        padding: dp(15)
        spacing: dp(10)
        MDLabel:
            text: 'Words'
        Words_Box:
            id: words_box
            orientation: 'vertical'
            padding: dp(15)
            spacing: dp(10)
        MDRaisedButton:
            text: 'CREATE LIST OF WORDS'
            on_release: root.ids.words_box.add_word_buttons()
'''


class Word_button(MDRaisedButton):
    correct = BooleanProperty()

    def check_word(self):
        print('Answer is ', self.correct)
        print('Button Text is ', self.text)


class Words_Box(MDBoxLayout):

    def add_word_buttons(self):
        app = MDApp.get_running_app()
        words = ['$WORD 1', 'WORD 2', 'WORD 3']
        for word in words:
            correct = False
            if '$' in word:
                correct = True
                word = word[1:]
            btn = Word_button(text=word, correct=correct)
            self.add_widget(btn)


class RootScreen(Screen):
    def __init__(self, **kwargs):
        super(RootScreen, self).__init__(**kwargs)


class Main(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.screen = Builder.load_string(kv)

    def build(self):
        return self.screen


Main().run()

1 Answers

This was resolved by not naming the kv file main.kv.

Related