Kivy开发求助:Python无法修改.kv文件中按钮文本
Kivy按钮文本无法更新的解决方案
问题根源及修正步骤
1. 类初始化方法错误嵌套
原代码中__init__方法被错误嵌套在generate_word函数内部,导致类初始化逻辑完全未执行,self.words未定义,初始词汇生成也不会触发。
修正: 将__init__移到WordGame类顶层,作为类的直接方法,并在初始化时调用generate_word。
2. KV文件中控件ID的引号错误
KV文件里Label的id: "word_label"使用了引号,导致Python代码中self.ids.word_label无法找到该控件(ID名被当作带引号的字符串)。
修正: 改为id: word_label,去掉引号。
3. 正确按钮映射逻辑颠倒
原代码创建correct_button的字典是{按钮: 翻译文本},却试图用正确翻译文本作为键取值,引发KeyError。
修正: 将字典改为{翻译文本: 按钮},通过正确翻译文本找到对应按钮实例。
4. 重复调用词汇生成方法
check_translation中连续调用两次generate_word,导致刚显示对错结果就立刻刷新词汇,用户无法看到反馈。
修正: 先判断对错并显示提示,再通过Clock.schedule_once延迟调用generate_word,给用户留足查看结果的时间。
5. 缺失必要模块导入
原代码未导入random、kivy.uix.boxlayout.BoxLayout等必要模块,运行会报错。
修正: 在代码开头添加所有必要的导入语句。
修正后的完整代码
Python代码(.py)
import random from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder from kivy.uix.screenmanager import ScreenManager, Screen from kivy.clock import Clock from kivymd.app import MDApp vocab = { "ability": ["schopnost", "cane", "chien"], "able": ["být schopen", "gatto", "chat"], "about": ["o", "maison", "casa"], "above": ["nad", "albero", "arbre"], "abroad": ["zahraničí", "libro", "livre"], "absorb": ["vstřebat", "assorbire", "absorber"], "abuse": ["zneužití", "abuso", "abus"], "accept": ["přijmout", "accettare", "accepter"], } class WordGame(BoxLayout): def __init__(self, **kwargs): super().__init__(**kwargs) self.words = list(vocab.keys()) self.generate_word() def generate_word(self): word = random.choice(self.words) translations = vocab[word].copy() random.shuffle(translations) self.ids.word_label.text = word self.ids.button1.text = translations[0] self.ids.button2.text = translations[1] self.ids.button3.text = translations[2] self.translation_to_button = { translations[0]: self.ids.button1, translations[1]: self.ids.button2, translations[2]: self.ids.button3 } self.correct_translation = vocab[word][0] def check_translation(self, instance): if instance.text == self.correct_translation: self.ids.word_label.text = "Correct!" else: self.ids.word_label.text = f"Incorrect! Correct is: {self.correct_translation}" Clock.schedule_once(lambda dt: self.generate_word(), 1.5) kv_files = ['splash.kv', 'login.kv', 'menu.kv', 'levelselect.kv', 'levelb1.kv', 'Charakter.kv', 'test.kv'] class Aplikace(MDApp): def build(self): global obraz obraz = ScreenManager() for file in kv_files: obraz.add_widget(Builder.load_file(file)) self.theme_cls.theme_style = "Dark" self.theme_cls.primary_palette = "Blue" return obraz def on_start(self): Clock.schedule_once(self.login, 1) def login(self, *args): obraz.current = "login" def levelselect(self): obraz.current = "levelselect" def log(self): obraz.current = "menu" def Event(self): obraz.current = "splash" def levelb1(self): obraz.current = "levelb1" def Forum(self): obraz.current = "splash" def Friendlist(self): obraz.current = "splash" def Leaderboard(self): obraz.current = "splash" def Charakter(self): obraz.current = "charakter" def test(self): obraz.current = "test" Aplikace().run()
KV代码(test.kv)
<WordGame>: BoxLayout: orientation: "vertical" size_hint: 1, 1 BoxLayout: size_hint_y: 0.2 BoxLayout: orientation:"horizontal" canvas.before: Color: rgba: 1, 0, 0, 1 Rectangle: pos: self.pos size: self.size size_hint_x: 1 size_hint_y: 0.4 Label: id: word_label text: "Click the correct translation" font_size: "24sp" bold: True text_size: self.width, None pos_hint: {'center_x': 0.5,'center_y': 0.5} halign: "center" BoxLayout: orientation: "horizontal" canvas.before: Color: rgba: 0, 1, 0, 1 Rectangle: pos: self.pos size: self.size spacing: 10 padding: 10 Button: size_hint: 1, 0.4 id: button1 text: "Option 1" on_release: root.check_translation(self) Button: size_hint: 1, 0.4 id: button2 text: "Option 2" on_release: root.check_translation(self) Button: size_hint: 1, 0.4 id: button3 text: "Option 3" on_release: root.check_translation(self) BoxLayout: size_hint_y: 0.2 Screen: name: "test" WordGame:
内容的提问来源于stack exchange,提问作者Kaeru
相关产品推荐
相关产品推荐

