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

KivyMD货币转换器:KV文件调用currency_mapping报错求助

解决KV文件调用currency_mapping报错的问题

问题根源

你在Currency_ConverterApp(MDApp子类)里定义了currency_mapping,但KV中的root指向的是当前部件的父容器(比如你的Screen实例),而非App类实例,所以root没有currency_mapping属性,导致报错。

解决方案

方案1:KV中改用app.currency_mapping调用

KV语言里可以直接用app关键字访问MDApp的实例,把KV里的root.currency_mapping改成app.currency_mapping即可:

MDIconButton:
    id: currency_button_1
    icon: app.currency_mapping[root.ids.currency_button_1.currency]
    on_release: app.change_currency(root.ids.currency_button_1.currency)

MDIconButton:
    id: currency_button_2
    icon: app.currency_mapping[root.ids.currency_button_2.currency]
    on_release: app.change_currency(root.ids.currency_button_2.currency)

方案2:将currency_mapping移到Screen类中

如果希望用root访问,需要把currency_mapping定义在对应的Screen子类里(假设你用的是ScreenManager管理的Screen):

class ConverterScreen(MDScreen):
    currency_mapping = {
        'USD': 'us.png',
        'EUR': '27018.png',
    }

class Currency_ConverterApp(MDApp):
    def build(self):
        return Builder.load_string(KV)
    
    # 其他方法...

此时KV里的root.currency_mapping就能正常访问,因为root是ConverterScreen的实例。

额外代码修正

你的change_currency方法里有个笔误:

screen.current_currency = currencyy  # 多了一个y,应为currency

修改为:

screen.current_currency = currency

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 11:48:13