如何在KivyMD中点击按钮时更新MDLabel的文本内容
Hey there! Let's get that text updating working in KivyMD. Coming from tkinter, the approach is a bit different but super simple once you get the hang of it. Here's how to fix your code:
Key Changes Needed:
- Call the app's function from KV language: Use
app.change_word()in the button'son_pressevent—apprefers directly to your runningAnsweredOrNotapp instance. - Access the MDLabel via its ID: In your
change_wordmethod, you don't need extra parameters beyondself. Just useself.root.ids['text-update']to grab the label (since your ID has a hyphen, dictionary-style access is safer; if you used underscores liketext_update, you could useself.root.ids.text_updateinstead for cleaner syntax). - Kivy auto-updates the UI: Unlike tkinter, you don't need to call an
update()method—changing the label'stextproperty will automatically refresh the display.
Modified Working Code:
from kivymd.app import MDApp from kivy.lang import Builder import random from kivy.core.window import Window Window.size=(400,600) please_anwser_this=""" MDScreen: MDLabel: id:text-update text:'Click The Button below to Change this text' halign:'center' pos_hint:{'center_x':0.5,'center_y':0.6} MDFillRoundFlatIconButton: text:'Change It' pos_hint:{'center_x':0.5,'center_y':0.5} icon:'crop-rotate' on_press: app.change_word() # Trigger the text update function here """ class AnsweredOrNot(MDApp): def build(self): builder=Builder.load_string(please_anwser_this) return builder def change_word(self): # No extra parameters required besides self site_list=['Google','Yahoo','Microsoft','APKpure','APKMB','Stackoverflow','Bing'] text=random.choice(site_list) # Access the label and update its text property self.root.ids['text-update'].text = text AnsweredOrNot().run()
Quick Tip:
For smoother ID access, try using underscores instead of hyphens in your widget IDs (e.g., text_update instead of text-update). This lets you write self.root.ids.text_update instead of the dictionary syntax, which feels a bit more intuitive.
内容的提问来源于stack exchange,提问作者ZARIR
相关产品推荐
相关产品推荐

