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

如何在Kivy按钮on_release中调用方法并传递按钮文本?

解决Kivy按钮点击传递文本调用方法的问题

问题分析

当前代码中my.kv里的GreyButton试图通过MyMainApp.button_input(self.text)调用方法,但button_input是MainWindow类的实例方法,并非MyMainApp类的方法,导致无法正确触发。需要调整kv文件中的调用逻辑,让按钮点击时能定位到MainWindow的实例并调用对应方法。

修改步骤

仅需修改my.kv文件中GreyButton的on_release事件代码:

  • 将原代码MyMainApp.button_input(self.text)替换为app.root.get_screen('main').button_input(self.text)
    • app指代当前运行的MyMainApp实例
    • app.root获取到WindowManager实例
    • get_screen('main')定位到名为main的MainWindow实例
    • 最终调用该实例的button_input方法并传入按钮文本self.text

修改后的完整代码

main.py(无需改动)

import kivy
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.layout import Layout
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.core.text import LabelBase
from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.config import Config
Config.set('graphics', 'width', '180')
Config.set('graphics', 'height', '380')
# Config.set('graphics', 'fullscreen', 0)
Config.write()

LabelBase.register(name='JBR', fn_regular='fonts/JetBrainsMono-Regular.ttf')

button_input_text = ""

class MainWindow(Screen):

    def button_input(self, inp):
        print(inp)


class WindowManager(ScreenManager):
    pass


Builder.load_file('my.kv')
sm = WindowManager()
screens = [MainWindow(name="main")]
for screen in screens:
    sm.add_widget(screen)


class MyMainApp(App):
    def build(self):
        return sm


if __name__ == "__main__":
    MyMainApp().run()

修改后的my.kv

<GreyButton@FloatLayout>:
    id: float_root
    size_hint: (None, None)
    text: ""
    bg_color: (0.2, 0.2, 0.2, 1)
    btn_size: (40,40)
    size: (40,40)
    pos_hint: {"x": 0.5, "y": 0.5}
    on_release:
        app.root.get_screen('main').button_input(self.text)  # 此处为修改核心
    Button:
        text: float_root.text
        font_name: "JBR"
        font_size: 19
        size_hint: (None, None)
        size: float_root.btn_size
        pos_hint: {"x": 0.25, "y": 0.25}
        background_normal: ""
        background_color: (0,0,0,0)
        canvas.before:
            Color:
                rgba: float_root.bg_color
            Ellipse:
                size: self.size
                pos: self.pos
        on_press:
            float_root.bg_color = (0.25, 0.25, 0.25, 1)
        on_release:
            float_root.bg_color = (0.2, 0.2, 0.2, 1)


WindowManager:
    MainWindow:

<MainWindow>:
    name: "main"

    FloatLayout:
        size: root.width, root.height

        GreyButton:
            text: "="
            pos_hint: {"right":0.9, "y":0}

验证效果

运行程序后点击按钮,控制台会输出按钮文本=,说明方法调用成功。后续添加更多GreyButton时,只需设置不同的text属性,点击时都会自动传递对应文本到button_input方法中。

内容的提问来源于stack exchange,提问作者cozycoder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:20:26