【发布时间】:2021-03-21 23:53:12
【问题描述】:
由于某种原因,Word_button 实例的 On Press 事件被触发了两次。下面的代码演示了这一点。
重复问题。
- 运行下面的代码
- 单击“创建单词列表”按钮。这将创建一个按钮列表。如果单词正确与否,每个按钮都有布尔属性。
- 然后单击单词按钮。单击按钮时,打印语句会打印正确的布尔变量和按钮文本。
问题:
- 打印命令运行两次。
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()
【问题讨论】:
-
无法重现您的问题。
-
谢谢@JohnAnderson,这可能是 Kivy 版本的问题吗?我正在使用 2.0.0 和 KivyMD 0.104.1。
-
版本可能是个问题,但我对此表示怀疑。您的代码两次声明
Word_button和Words_Box,这可能是问题所在。尝试将<Word_button@MDRaisedButton>:更改为<Word_button>:,并将<Words_Box@MDBoxLayout>:更改为<Words_Box>:。 -
再次感谢@JohnAnderson,我想我设法通过将我的 .kv 文件从 main.kv 重命名为 words.kv 来解决它。认为在 kv 文件中使用该文件名存在某种冲突。