You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在KivyMD中点击按钮时更新MDLabel的文本内容

How to Update MDLabel Text on Button Press in KivyMD

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's on_press event—app refers directly to your running AnsweredOrNot app instance.
  • Access the MDLabel via its ID: In your change_word method, you don't need extra parameters beyond self. Just use self.root.ids['text-update'] to grab the label (since your ID has a hyphen, dictionary-style access is safer; if you used underscores like text_update, you could use self.root.ids.text_update instead for cleaner syntax).
  • Kivy auto-updates the UI: Unlike tkinter, you don't need to call an update() method—changing the label's text property 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:34:06