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

如何在Kivy的kv文件中调用Account类的方法?

How to Call getBalance() from Account Class in Kivy KV File

Got it, let's get your account balance showing up in that Label. Here's what you need to adjust in your code, step by step:

First, Fix the Account Class (Critical!)

Right now you're initializing balance as a string "1000"—that'll break your setBalance() method later when you try to add numbers to it. Let's switch it to an integer:

class Account():
    def __init__(self, name, balance):
        self.name = name
        # Use integer instead of string for balance to enable math operations
        self.__balance__ = int(balance)
    def getBalance(self):
        return self.__balance__
    def setBalance(self, zmena):
        # Convert input to int too, since user input will be a string
        self.__balance__ += int(zmena)

Make the Account Instance Accessible to KV

Your current acc is a global variable, which KV can't easily reference. Instead, attach it to your MainApp class so KV can access it via the app keyword:

import kivy
kivy.require("1.10.1")
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget

class Account():
    def __init__(self, name, balance):
        self.name = name
        self.__balance__ = int(balance)
    def getBalance(self):
        return self.__balance__
    def setBalance(self, zmena):
        self.__balance__ += int(zmena)

class myWidget(Widget):
    pass  # Move KV loading to the App class for cleaner structure

class MainApp(App):
    def build(self):
        # Create the Account instance here and attach it to the app
        self.acc = Account("Account1", "1000")
        # Load the KV file in build() instead of the widget class
        Builder.load_file("MP.kv")
        return myWidget()

    def update_balance(self, amount):
        # Helper method to handle button clicks and update the balance
        self.acc.setBalance(amount)

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

Update the KV File to Display the Balance

Now you can bind the Label's text to app.acc.getBalance(), converting it to a string since Kivy Labels expect text content. We'll also add logic to the Confirm button to update the balance when clicked:

#:kivy 1.10.1
<Button>
    background_color: 0.1, 0.1, 0.9, 0.9
    font_size: 22
<Label>
    background_color: 0.1, 0.1, 0.9, 0.9
    font_size: 22
<myWidget>:
    Label:
        id: lb
        text: "Account"
        pos: root.width /2-self.width/2, root.top/2+200
    Label:
        id: lb1
        text: f"Account name: {app.acc.name}"
        pos: root.width /2-self.width/2, root.top/2+150
    Label:
        id: lb2
        # Call getBalance() and convert to string for display
        text: f"balance: {str(app.acc.getBalance())}"
        pos: root.width /2-self.width/2, root.top/2+100
    Label:
        id: lb3
        text: "Add/sub money"
        pos: root.width /2-self.width/2, root.top/2+50
    TextInput:
        id: tp
        hint_text: "Enter amount (positive to add, negative to subtract)"
        pos: root.width /2-self.width/2, root.top/2-50
        size_hint: .5, .25
        input_filter: "int"  # Restrict input to integers to avoid errors
    Button:
        id: btn1
        text: "Confirm"
        size_hint: .5, .25
        pos: root.width /2-self.width/2, root.top/2-150
        # Trigger the app's update method when clicked
        on_press: app.update_balance(tp.text)

Why This Works:

  • By attaching the acc instance to MainApp, KV can access it using the app keyword (which refers to your running app instance).
  • We convert the balance to a string in KV because the Label's text property requires a string value.
  • The input_filter: "int" on the TextInput ensures users can only enter valid numbers, preventing errors in the setBalance() method.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:34:04