首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python+kivy+SQLite:如何将它们结合使用

Python+kivy+SQLite:如何将它们结合使用
EN

Stack Overflow用户
提问于 2016-08-14 05:23:41
回答 1查看 10.8K关注 0票数 6

我对python,kivy和sqlite都很陌生。但我必须完成这个艰巨的任务。提前感谢!

任务是:在android上的.db屏幕上显示来自kivy文件的数据。

我用http://zetcode.com/db/sqlitepythontutorial/制作了数据库文件

在这里,我再次发布代码。

代码语言:javascript
运行
复制
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('test.db')

with con:

    cur = con.cursor()    
    cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
    cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)")
    cur.execute("INSERT INTO Cars VALUES(2,'Mercedes',57127)")
    cur.execute("INSERT INTO Cars VALUES(3,'Skoda',9000)")
    cur.execute("INSERT INTO Cars VALUES(4,'Volvo',29000)")
    cur.execute("INSERT INTO Cars VALUES(5,'Bentley',350000)")
    cur.execute("INSERT INTO Cars VALUES(6,'Citroen',21000)")
    cur.execute("INSERT INTO Cars VALUES(7,'Hummer',41400)")
    cur.execute("INSERT INTO Cars VALUES(8,'Volkswagen',21600)")

然后将数据库保存到C:\\test.db中。

然后,我用labelbutton制作了一个button屏幕。

代码语言:javascript
运行
复制
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder

import random

root_widget = Builder.load_string('''
BoxLayout:
    orientation: 'vertical'
    Label:
        text: 'Hello'  #How to define it?
        font_size: 30
    Button:
        size: root.width/2, 15
        text: 'next random'
        font_size: 30
#        on_release:  #How to define it?
''')

class TestApp(App):
    def build(self):
        return root_widget

if __name__ == '__main__':
    TestApp().run()

我希望在每次单击random 的汽车名为时,从label上显示button

最初的label文本,现在是单词"Hello",应该替换为一个随机的汽车名称。这样,每次运行程序时,label上都会显示一个汽车名称。

但是我真的不知道怎么写代码。

谢谢你的帮助。

#更新

代码是我写的,但不起作用。

代码语言:javascript
运行
复制
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.clock import mainthread
import sqlite3

import random


class MyBoxLayout(BoxLayout):

    def init(self, **kwargs):
        super().__init__(**kwargs)

        @mainthread  # execute within next frame
        def delayed():
            self.load_random_car()
        delayed()

    def load_random_car(self):
        conn = sqlite3.connect("C:\\test.db")
        cur = conn.cursor()

        ####Length of db file
        with conn:
            cur = conn.cursor()
            cur.execute("SELECT * FROM Cars")
            rows = cur.fetchall()
        LengthSQLFile = len(rows)
        print LengthSQLFile


        CurrentNo = random.randint(0, LengthSQLFile)
        CurrentNo_ForSearch = (CurrentNo ,)
        cur.execute("select * from Cars where rowid = ?" , CurrentNo_ForSearch)

        CurrentAll = cur.fetchone()
        CurrentAll = list(CurrentAll)   # Change it from tuple to list
        print CurrentAll

        Current    = CurrentAll[1]
        self.ids.label.text = Current #"fetch random car data from db and put here"


root_widget = Builder.load_string('''
BoxLayout:
    orientation: 'vertical'
    Label:
        id: label
        font_size: 30
    Button:
        size: root.width/2, 15
        text: 'next random'
        font_size: 30
        on_release:  root.load_random_car()

''')


class TestApp(App):
    def build(self):
#        MyBoxLayout(BoxLayout)
        return root_widget

if __name__ == '__main__':
    TestApp().run()

#2更新:

现在的密码是..。它显示了错误消息:AttributeError: 'BoxLayout' object has no attribute 'load_random_car'

代码语言:javascript
运行
复制
# -*- coding: utf-8 -*-

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.clock import mainthread
import sqlite3

import random

class MyBoxLayout(BoxLayout):

    def init(self, **kwargs):
        super().__init__(**kwargs)

        @mainthread  # execute within next frame
        def delayed():
            self.load_random_car()
        delayed()

    def load_random_car(self):
        conn = sqlite3.connect("C:\\test.db")
        cur = conn.cursor()

        cur.execute("SELECT * FROM Cars ORDER BY RANDOM() LIMIT 1;")

        currentAll = cur.fetchone()
        currentAll = list(currentAll)   # Change it from tuple to list
        print currentAll

        current    = currentAll[1]
        self.ids.label.text = current #"fetch random car data from db and put here"


root_widget = Builder.load_string('''
BoxLayout:
    orientation: 'vertical'
    Label:
        id: label
        font_size: 30
    Button:
        size: root.width/2, 15
        text: 'next random'
        font_size: 30
        on_release:  root.load_random_car()

''')


class TestApp(App):
    def build(self):
#        MyBoxLayout(BoxLayout)
        return root_widget

if __name__ == '__main__':
    TestApp().run()
EN

Stack Overflow用户

回答已采纳

发布于 2016-08-14 14:50:12

最简单的方法是为框布局编写自定义的init方法:

代码语言:javascript
运行
复制
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import mainthread

class MyBoxLayout(BoxLayout):

    def init(self, **kwargs):
        super().__init__(**kwargs)

        @mainthread  # execute within next frame
        def delayed():
            self.load_random_car()
        delayed()

    def load_random_car(self):
        self.ids.label.text = "fetch random car data from db and put here"

更新后的小部件结构如下所示:

代码语言:javascript
运行
复制
MyBoxLayout:
    Label:
        id: label
    Button:
        on_release:  root.load_random_car()
票数 5
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38939416

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档