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

Python-2.7与Kivy-1.9.0中如何设置Button的id?

Hey there! Let's figure out why you're getting that 'Alert' object has no attribute 'test' error when trying to set a Button's ID in Kivy 1.9.0 with Python 2.7.

First off, it's important to understand how Kivy's id system works. When you define an id in a kv language file, Kivy automatically adds that widget instance to the parent widget's ids dictionary, letting you access it with self.ids.your_id. But when you create a widget directly in Python code and set the id parameter, that id is just an attribute of the button itself—it doesn't get automatically linked to the parent Alert widget's properties or ids dict. That's why trying to call self.test throws an error: your Alert object never got a test attribute assigned to it.

Solution 1: Manually add the button to the parent's ids dictionary

If you want to stick with creating the button in Python, you can manually add it to your Alert widget's ids dict after creating it. This lets you use Kivy's ids system to access it later:

btn1 = Button(text="Close", id="test")
self.ids['test'] = btn1  # Add the button to the ids dict
# Now you can access it with self.ids.test

Solution 2: Assign the button directly as an attribute of your Alert

If you don't need to use Kivy's ids system, just assign the button as a direct attribute of your Alert class. This is straightforward and avoids dealing with the ids dict:

self.test = Button(text="Close")
# Now you can access it directly with self.test, no id needed

Kivy's design is optimized for using kv language to define UI layouts, which handles id mapping automatically. If your Alert is a custom widget, create a kv file (or use Builder strings) to define it:

<Alert>:
    Button:
        text: "Close"
        id: test
        # Add any on_press logic here, like calling a method in your Alert class
        on_press: root.close_popup()

Then in your Python Alert class, you can access the button using self.ids.test without any extra setup.

To recap, your original code only set the button's own id attribute, but didn't link it to your Alert widget. Pick the solution that fits how you're structuring your app—using kv is generally the most "Kivy-idiomatic" way, but the other options work great for dynamic UI elements.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:44:43