【问题标题】:How can display data from the database to kivy table如何将数据库中的数据显示到kivy表
【发布时间】:2021-09-09 16:17:14
【问题描述】:

我想在其中一个屏幕上显示一个表格,表格中显示的数据应该来自贷款数据库,贷款表。

我已经创建了数据库,并且没有显示任何错误。表已创建,但没有显示任何数据。它是空表。

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
import json
from kivy.uix.boxlayout import BoxLayout
 
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
 
from loandatabase import Database
database = Database()
 
Builder.load_file('design.kv')
 
class MainScreen(Screen):
    def goto_admin_page(self):
        self.manager.current = "adminfirst_screen"
    def goto_agent_page(self):
        pass
    def goto_customer_page(self):
        pass
 
class AdminScreenFirst(Screen):
    def go_to_adminsecond(self,uname,pword):
        with open("users.json") as file:
            users =json.load(file)
            if uname in users and users[uname]['password'] == pword:
                self.manager.current = "adminsecond_screen"
            else:
                self.ids.login_wrong.text = "Invalid Credentials.Please Contact the administrator"
 
class AdminScreenSecond(Screen):
    def go_to_adminpending(self):
        self.manager.current = "adminPending_screen"
    def go_to_adminapproved(self):
        self.manager.current = "adminsecond_screen"
    def go_to_adminrejected(self):
        self.manager.current = "adminsecond_screen"
 
class AdminPendingScreen(Screen):
    def display(self):
        self.manager.current = "rv_screen"
class RV(Screen):
    data_items = ListProperty([])
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
  
        for row in database.view():
            for col in row:
                self.data_items.append(col)
    
 
class TextInputPopup(Popup):
    obj = ObjectProperty(None)
    obj_text = StringProperty("")
 
    def __init__(self, obj, **kwargs):
        super(TextInputPopup, self).__init__(**kwargs)
        self.obj = obj
        self.obj_text = obj.text
 
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
                                  RecycleGridLayout):
    ''' Adds selection and focus behaviour to the view. '''
class SelectableButton(RecycleDataViewBehavior, Button):
    ''' Add selection support to the Label '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)
    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableButton, self).refresh_view_attrs(
            rv, index, data)
 
    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableButton, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)
 
    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view. '''
        self.selected = is_selected
 
    def on_press(self):
        popup = TextInputPopup(self)
        popup.open()
 
    def update_changes(self, txt):
        self.text = txt
 
class RootWidget(ScreenManager):
    pass
 
class MainApp(App):
    def build(self):
        return RootWidget()
 
 
if __name__ == "__main__":
    MainApp().run()

我的 kivy 代码:

<MainScreen>:
    GridLayout:
        cols:1
        GridLayout:
            cols:1
            padding:15,15
            spacing:20,20
            Label:
                text:"Login"
                font_size:"20sp"
            Button:
                text:"Admin"
                on_press : root.goto_admin_page()
            Button:
                text:"Agent"
                on_press : root.goto_agent_page()
            Button:
                text: "Customer"
                on_press:root.goto_customer_page()
 
<AdminScreenFirst>:
    GridLayout:
        cols:1
        padding:15,15
        spacing:20,20
        Label:
            text:"Admin Login"
            font_size:"20sp"
        TextInput:
            id:username
            hint_text:"Username"
        TextInput:
            id:password
            password:True
            hint_text:"Password"
        RelativeLayout:
            Button:
                text:"Login"
                on_press : root.go_to_adminsecond(root.ids.username.text,root.ids.password.text)
                size_hint :0.3,0.5
                pos_hint: {'center_x' : 0.5 , 'center_y' : 0.6}
        Label:
            id:login_wrong
            text:""
<AdminScreenSecond>:
    GridLayout:
        cols:1
        padding:15,15
        spacing:20,20
        Label:
            text:"Loan"
            font_size:"20sp"
        Button:
            text:"Pending Request"
            on_press:root.go_to_adminpending()
        Button:
            text:"Approved"
            on_press: root.go_to_adminapproved()
        Button:
            text:"Rejected"
            on_press: root.go_to_adminrejected()
 
<AdminPendingScreen>:
    GridLayout:
        cols:1
        padding:15,15
        spacing:20,20
        Label:
            text:"Loans"
        Button:
            text:"Display"
            on_press: root.display()
        Label:
            id:display
            text:""
<TextInputPopup>:
    title: "Popup"
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False
 
    BoxLayout:
        orientation: "vertical"
        TextInput:
            id: txtinput
            text: root.obj_text
        Button:
            size_hint: 1, 0.2
            text: "Save Changes"
            on_release:
                root.obj.update_changes(txtinput.text)
                root.dismiss()
        Button:
            size_hint: 1, 0.2
            text: "Cancel Changes"
            on_release: root.dismiss()
 
<RV>:
    BoxLayout:
        orientation: "vertical"
 
        GridLayout:
            size_hint: 1, None
            size_hint_y: None
            height: 25
            cols: 11
            Label:
                text: "LoanID"
            Label:
                text: "Name"
            Label:
                text:"Tenure"
            Label:
                text:"Balance"
            Label:
                text:"LoanType"
            Label:
                text:"InterestType"
            Label:
                text:"Interest % p.a."
            Label:
                text:"Security"
            Label:
                text:"Total"
            Label:
                text:"EMI"
            Label:
                text:"Request"
 
        BoxLayout:
            RecycleView:
                viewclass: 'SelectableButton'
                data: [{'text': str(x)} for x in root.data_items]
                SelectableRecycleGridLayout:
                    cols: 11
                    default_size: None, dp(26)
                    default_size_hint: 1, None
                    size_hint_y: None
                    height: self.minimum_height
                    #orientation: 'vertical'
                    multiselect: True
                    touch_multiselect: True
 
<RootWidget>:
    MainScreen:
        name:"mainfirst_screen"
    AdminScreenFirst:
        name:"adminfirst_screen"
    AdminScreenSecond:
        name:"adminsecond_screen"
    AdminPendingScreen:
        name:"adminPending_screen"
    RV:
        name:"rv_screen"

我的数据库代码:

import sqlite3
 
 
class Database:
    def __init__(self):
        self.conn = sqlite3.connect("loandatabase.db")
        self.cur = self.conn.cursor()
        self.cur.execute("CREATE TABLE IF NOT EXISTS loan (id INTEGER PRIMARY KEY, customer_name TEXT, tenure integer, balance integer, loantype TEXT, interesttype TEXT,interest integer,security TEXT,totalpayment integer,emi integer,instruction TEXT)")
        self.conn.commit()
 
    def insert(self,cname,tenure,blance,ltype,itype,interest,security,tpay,emi,instr):
        self.cur.execute("INSERT INTO loan VALUES (NULL,?,?,?,?,?,?,?,?,?,?)",(cname,tenure,blance,ltype,itype,interest,security,tpay,emi,instr))
        self.conn.commit()
 
    def view(self):
        self.cur.execute("SELECT * FROM loan")
        rows = self.cur.fetchall()
        return rows
 
    def __del__(self):
        self.conn.close()

[![在此处输入图片描述][1]][1]

我会请求你帮助我解决这个问题。先感谢您 我正在使用 Kivy、Python、sqlite3

显示如下: [1]:https://i.stack.imgur.com/fkUvS.png

【问题讨论】:

  • 让我们看看你的代码做了什么。你调用 MainApp.run()。这大概会调用 MainApp.build()。 MainApp.build() 返回从 kivy ScreenManager 派生的 RootWidget。而已。这就是它所做的一切。你的其他代码都没有被使用过。不知何故(我不知道 kivy)你必须告诉它要使用哪些类,或者在哪里可以找到你的 kivy 代码。你错过了那个连接。
  • 我的 rootwidget 是屏幕管理器,它将获取第一个屏幕并显示它。我已经使用 builder statment 加载了 kivy 文件
  • 你不需要打电话给add_widget 告诉 ScreenManager 你的课程吗?

标签: python python-3.x sqlite kivy kivy-language


【解决方案1】:

试试这个:

class MainApp(App):
    title = 'Title of the app'
    
    def build(self):
        sm = ScreenManager('''You can add transition here''')
        sm.add_widget(MainScreen(name='main'))
        sm.add_widget(AdminScreenFirst(name='admin1'))
        sm.add_widget(AdminScreenSecond(name='admin2'))
        sm.add_widget(AdminPendingScreen(name='pending'))
        sm.add_widget(RV(name='rv'))
        return sm

【讨论】:

    猜你喜欢
    • 2018-04-11
    • 2016-08-03
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    相关资源
    最近更新 更多