Skip to main content
 首页 » 编程设计

python之可以在 python 中使用循环来选择 kivy ids 吗

2024年10月01日6sky-heaven

你好,我可以使用循环选择多个 kivy id 吗?假设我有 3 个 id(一、二、三) 我从数据库中选择 id,比如 c 是 kivy 小部件的 id。

kvids=0 
while kvids < 3 
    c=select 'kivy id'#pseudocode 
    self.ids.c.text='not work' 

有没有可能使用这样的东西?或者对于这样的事情还有其他简单的解决方案吗?我需要从数据库中选择一些信息并将其绑定(bind)到小部件。我对此一无所知。 千伏:

Button: 
    id:one 
Button: 
    id:two 
Button: 
    id:three 

我没有粘贴所有代码,因为无论代码看起来如何,我只需要解决方案。

请您参考如下方法:

是的,这是可以做到的。详情请引用以下示例。

当你的 kv 文件被解析时,kivy 收集所有标有 id 的小部件并将它们放在这个 self.ids 字典类型属性中。这意味着您还可以遍历这些小部件并访问它们的字典样式:

for key, val in self.ids.items(): 
    print("key={0}, val={1}".format(key, val)) 

或

self.ids['one'].text = "Button 1" 

或

self.ids.two.text = 'Button 2' 

例子

主.py
import sqlite3 
 
from kivy.app import App 
from kivy.uix.boxlayout import BoxLayout 
 
 
class DemoKivyIDsDB(BoxLayout): 
    def __init__(self, **kwargs): 
        super(DemoKivyIDsDB, self).__init__(**kwargs) 
        self.set_widgets_text() 
 
    def set_widgets_text(self): 
        connection = sqlite3.connect("kivy.db") 
        cursor = connection.cursor() 
 
        cursor.execute("SELECT widget_id FROM kivyids") 
        print("fetchall:") 
        result = cursor.fetchall() 
        for r in result: 
            print(r) 
            self.ids[r[0]].text = "not work" 
 
 
class TestApp(App): 
    def build(self): 
        return DemoKivyIDsDB() 
 
 
if __name__ == "__main__": 
    TestApp().run() 

测试.kv

#:kivy 1.10.0 
 
<DemoKivyIDsDB>: 
    Button: 
        id: one 
    Button: 
        id: two 
    Button: 
        id: three 

KivyIDsDB.py
import sqlite3 
 
connection = sqlite3.connect("kivy.db") 
 
cursor = connection.cursor() 
 
# delete 
# cursor.execute("""DROP TABLE kivyids;""") 
 
sql_command = """ 
CREATE TABLE kivyids ( 
id INTEGER PRIMARY KEY, 
widget_id VARCHAR(20), 
widget_text VARCHAR(30)); 
""" 
 
# create table 
cursor.execute(sql_command) 
 
sql_command = """ 
INSERT INTO kivyids (id, widget_id, widget_text) 
VALUES (NULL, 'one', 'Button 1'); 
""" 
 
cursor.execute(sql_command) 
 
sql_command = """ 
INSERT INTO kivyids (id, widget_id, widget_text) 
VALUES (NULL, 'two', 'Button 2'); 
""" 
 
cursor.execute(sql_command) 
 
sql_command = """ 
INSERT INTO kivyids (id, widget_id, widget_text) 
VALUES (NULL, 'three', 'Button 3'); 
""" 
 
cursor.execute(sql_command) 
 
connection.commit() 
 
connection.close() 

输出