首页 > 解决方案 > 从数据库更新 ScrollView 中的按钮文本

问题描述

我正在编写一个使用 ScrollView 和 sqlite 数据库的 Kivy 应用程序。一旦在前一个屏幕中按下按钮,我想用数据库中的数据填充 ScrollView 按钮的按钮文本。到目前为止,我无法让它工作。

我从这里得到了我的滚动视图:KIVY python - 在布局中滚动视图

更新:我一直在 init 方法中使用 Clock ,实际上我得到了它来填充文本,条件是我在Clock.schedule_once. 我尝试过使用触发器来实现没有时间限制的类似效果,但没有成功。

主文件

p = Person()
dm = DataManager()

#...

class BasicProfileScreen(Screen):
container = ObjectProperty(None)

def __init__(self, **kwargs):
    super(BasicProfileScreen, self).__init__(**kwargs)
    Clock.schedule_once(self.create_scrollview, 10)

def load_info(self, name):
    dm.read("Basic_Profile", name)

def create_scrollview(self, dt):
    base = ["element {}".format(i) for i in range(4)]
    n = 0
    layout = GridLayout(cols=1, spacing=15, size_hint_y=None, padding=40)
    layout.bind(minimum_height=layout.setter("height"))
    while n < 2:
        layout.add_widget(Button(on_press=partial(self.nav_to_char_profile),
                                 text="Load from people.sqlite here", #<--the source of my frustration
                                 font_size=25,
                                 size=(50, 50), size_hint=(1, None),
                                 background_normal='normal.png',
                                 background_down='down.png'))
        n = n+1
    print(self.name_list)
    layout.add_widget(Button(on_press=partial(self.nav_to_char_profile), text="Back", font_size=25, size=(50, 50),
                             size_hint=(.50, None),
                             background_normal='normal.png',
                             background_down='down.png'))
    scrollview = ScrollView(size_hint=(1, None), size=(Window.width, Window.height))
    scrollview.add_widget(layout)
    self.container.add_widget(scrollview)

#...

)

从 Database.py 读取和写入

def write(self, pid, nom, age, sex, height, weight):
    write_string="INSERT INTO Basic_Profile (id, name) "+"values (null, %s);" % ("'"+nom+"'")
    dm.execute([write_string])

def read(self, table, nom):
    l = []
    queries = ['SELECT * FROM ' + table + ' WHERE name = ' + '"' + nom + '"' + ';']
    for result in dm.execute(queries):
        for row in result[0]:
            l.append(row)
    return l[1]

标签: pythonpython-3.xsqlitekivy

解决方案


您需要在您的 select 语句中调用 .fetchone() 或 .fetchall() 。在我看来, .fetchall() 在这里适合您的具体情况。fetcall() 返回一个列表,所以这应该可以工作(未经测试)

def read(self, table, nom):
    l = []
    queries = ['SELECT * FROM ' + table + ' WHERE name = ' + '"' + nom + '"' + ';']
    for result in dm.execute(queries).fetchall():
        for row in result[0]:
            l.append(row)
    return l[1]

否则请查看此处的示例: https ://docs.python.org/3/library/sqlite3.html


推荐阅读