我正在制作一个打字练习程序,我想检查每次输入字符时是否有人在TextInput中键入了正确的短语。
我尝试使用keyboard_on_key_down:root.CheckIfCorrect()运行该函数,并且在单击文本输入框时出现错误。 https://pastebin.com/nqU7bXcn
这是我的代码 main.py
from kivy.config import Config
Config.set('graphics', 'resizable', True)
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.core.window import Window
from kivy.properties import StringProperty
from kivy.uix.textinput import TextInput
import random
Builder.load_file("main.kv")
sentences = [
"My own brother, Aberforth, was prosecuted for practicing inappropriate charms on a goat. It was all over the papers, but did Aberforth hide? No, he did not! He held his head high and went about his business as usual! Of course, I'm not entirely sure he can read, so that may not have been bravery."
]
class TitleScreen(Screen):
def SwitchMain(self):
sm.switch_to(MainScreen(name="main"))
class MainScreen(Screen):
chosen = random.choice(sentences)
def CheckIfCorrect(self):
if self.chosen.startswith(self.ids.input.text) == True:
print("Correct")
else:
print("worng")
sm = ScreenManager()
sm.add_widget(TitleScreen(name='menu'))
sm.add_widget(MainScreen(name='settings'))
class TyperApp(App):
def build(self):
return sm
if __name__ == '__main__':
TyperApp().run()
main.kv
<TitleScreen>:
on_touch_up: root.SwitchMain()
BoxLayout:
orientation: "vertical"
Label:
text: "Welcome to Typer!"
font_size: 40
size_hint_y:2
Label:
text: "Click anything to begin..."
size_hint_y:1
<MainScreen>:
BoxLayout:
id:layout
orientation: "vertical"
Label:
id: lab
text: root.chosen
font_size: 25
padding: 10, 0
text_size: root.width, None
size: self.texture_size
size_hint_y:3
TextInput:
id: input
size_hint_y:2
multiline: False
#keyboard_on_key_down/up: root.CheckIfCorrect() This didn't work!
我希望每次键入正确的命令时,它都会在控制台中打印“正确”;而键入错误的命令时,它会输出“错误”。如果此人稍后输入错误,我将添加更多阻止其输入的内容。