Kivy中的属性错误,超级对象没有属性'__getattr__'

时间:2019-12-05 01:49:52

标签: python kivy pos

我在尝试运行代码时遇到一些问题,我不知道该怎么办,希望你们能帮助我解决这个问题

我将显示出现这些错误的文件:

admin.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.spinner import Spinner
from kivy.clock import Clock
from kivy.uix.modalview import ModalView
from kivy.lang import Builder

from collections import OrderedDict
from pymongo import MongoClient
from utils.datatable import DataTable
from datetime import datetime
import hashlib
import pandas as pd
import matplotlib.pyplot as plt
from kivy.garden.matplotlib.backend_kivyagg import FigureCanvasKivyAgg as FCK

Builder.load_file('admin/admin.kv')

class Notify(ModalView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.size_hint = (.7,.7)

class AdminWindow(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        mongoClient = MongoClient()
        db = mongoClient.consumini
        self.users = db.users
        self.products = db.stocks
        self.clients = db.clients
        self.notify = Notify()

        product_code = []
        product_name = []
        spinvals = []
        for product in self.products.find():
            product_code.append(product['product_code'])
            name = product['product_name']
            if len(name) > 30:
                name = name[:30] + '...'
            product_name.append(name)

        for x in range(len(product_code)):
            line = ' | '.join([product_code[x],product_name[x]])
            spinvals.append(line)
        self.ids.target_product.values = spinvals

        content = self.ids.scrn_contents
        users = self.get_users()
        users_table = DataTable(table=users)
        content.add_widget(users_table)

        #Display Products
        product_scrn = self.ids.scrn_product_contents
        products = self.get_products()
        prod_table = DataTable(table=products)
        product_scrn.add_widget(prod_table)

    def logout(self):
        self.parent.parent.current = 'scrn_si'

    def add_client_fields(self):
        target = self.ids.ops_fields_c
        target.clear_widgets()
        crud_name = TextInput(hint_text='Name',multiline=False)
        crud_birth = TextInput(hint_text='Birth Date',multiline=False)
        crud_gender = Spinner(text='Gender',values=['Female','Male'])
        crud_submit = Button(text='Add',size_hint_x=None,width=100,on_release=lambda x: self.add_client(crud_name.text,crud_birth.text,crud_gender.text))

        target.add_widget(crud_name)
        target.add_widget(crud_birth)
        target.add_widget(crud_gender)
        target.add_widget(crud_submit)

    def add_user_fields(self):
        target = self.ids.ops_fields
        target.clear_widgets()
        crud_name = TextInput(hint_text='Name',multiline=False)
        crud_user = TextInput(hint_text='User Name',multiline=False)
        crud_pwd = TextInput(hint_text='Password',multiline=False)
        crud_des = Spinner(text='Operator',values=['Operator','Admin'])
        crud_submit = Button(text='Add',size_hint_x=None,width=100,on_release=lambda x: self.add_user(crud_name.text,crud_user.text,crud_pwd.text,crud_des.text))

        target.add_widget(crud_name)
        target.add_widget(crud_user)
        target.add_widget(crud_pwd)
        target.add_widget(crud_des)
        target.add_widget(crud_submit)

    def add_product_fields(self):
        target = self.ids.ops_fields_p
        target.clear_widgets()

        crud_code = TextInput(hint_text='Product Code',multiline=False)
        crud_name = TextInput(hint_text='Product Name',multiline=False)
        crud_stock = TextInput(hint_text='Product In Stock',multiline=False)
        #crud_price = TextInput(hint_text='Product Price',multiline=False)
        crud_sold = TextInput(hint_text='Products Sold',multiline=False)
        crud_order = TextInput(hint_text='Ordered',multiline=False)
        crud_purchase = TextInput(hint_text='Last Purchase',multiline=False)
        crud_submit = Button(text='Add',size_hint_x=None,width=100,on_release=lambda x: self.add_product(crud_code.text,crud_name.text,crud_stock.text,crud_sold.text,crud_order.text,crud_purchase.text))

        target.add_widget(crud_code)
        target.add_widget(crud_name)
        target.add_widget(crud_stock)
        #target.add_widget(crud_price)
        target.add_widget(crud_sold)
        target.add_widget(crud_order)
        target.add_widget(crud_purchase)
        target.add_widget(crud_submit)

    def add_user(self, name,user,pwd,des):

        pwd = hashlib.sha256(pwd.encode()).hexdigest()
        if name == '' or user == '' or pwd == '':
            self.notify.add_widget(Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch,1)
        else:
            self.users.insert_one({'name':name,
        'username':user,'password':pwd,'designation':des,'date':datetime.now()})
            content = self.ids.scrn_contents
            content.clear_widgets()

            users = self.get_users()
            users_table = DataTable(table=users)
            content.add_widget(users_table)

    def add_client(self,name,birth,gender):

        if name == '' or birth == '' or gender == '':
            self.notify.add_widget(Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch,1)
        else:
            self.clients.insert_one({'name':name,
        'birthdate':birth,'gender':gender,'date':datetime.now()})
            content = self.ids.scrn_client_contents
            content.clear_widgets()

            clients = self.get_clients()
            clients_table = DataTable(table=clients)
            content.add_widget(clients_table)

    def killswitch(self,dtx):
        self.notify.dismiss()
        self.notify.clear_widgets()

    def add_product(self,code,name,stock,sold,order,purchase):

        if code == '' or name == '' or stock == '' or order == '': 
            self.notify.add_widget(Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch,1)
        else:
            self.products.insert_one({'product_code':code,'product_name':name,'in_stock':stock,'sold':sold,'order':order,'last_purchase':purchase})
            content = self.ids.scrn_product_contents
            content.clear_widgets()

            products = self.get_products()
            stock_table = DataTable(table=products)
            content.add_widget(stock_table)

    def update_user_fields(self):
        target = self.ids.ops_fields
        target.clear_widgets()
        crud_name = TextInput(hint_text='Name',multiline=False)
        crud_user = TextInput(hint_text='User Name',multiline=False)
        crud_pwd = TextInput(hint_text='Password',multiline=False)
        crud_des = Spinner(text='Operator',values=['Operator','Admin'])
        crud_submit = Button(text='Update',size_hint_x=None,width=100,on_release=lambda x: self.update_user(crud_name.text,crud_user.text,crud_pwd.text,crud_des.text))

        target.add_widget(crud_name)
        target.add_widget(crud_user)
        target.add_widget(crud_pwd)
        target.add_widget(crud_des)
        target.add_widget(crud_submit)

    def update_client_fields(self):
        target = self.ids.ops_fields_c
        target.clear_widgets()
        crud_first_name = TextInput(hint_text='First Name',multiline=False)
        crud_last_name = TextInput(hint_text='Last Name',multiline=False)
        crud_birth = TextInput(hint_text='Birth Date',multiline=False)
        crud_gender = Spinner(text='Gender',values=['Female','Male'])
        crud_submit = Button(text='Update',size_hint_x=None,width=100,on_release=lambda x: self.update_client(crud_first_name.text,crud_last_name.text,crud_birth.text,crud_gender.text))

        target.add_widget(crud_first_name)
        target.add_widget(crud_last_name)
        target.add_widget(crud_birth)
        target.add_widget(crud_gender)
        target.add_widget(crud_submit)

    def update_product_fields(self):
        target = self.ids.ops_fields_p
        target.clear_widgets()

        crud_code = TextInput(hint_text='Product Code',multiline=False)
        crud_name = TextInput(hint_text='Product Name',multiline=False)
        crud_stock = TextInput(hint_text='Product In Stock',multiline=False)
        #crud_price = TextInput(hint_text='Product Price',multiline=False)
        crud_sold = TextInput(hint_text='Products Sold',multiline=False)
        crud_order = TextInput(hint_text='Ordered',multiline=False)
        crud_purchase = TextInput(hint_text='Last Purchase',multiline=False)
        crud_submit = Button(text='Update',size_hint_x=None,width=100,on_release=lambda x: self.update_product(crud_code.text,crud_name.text,crud_stock.text,crud_sold.text,crud_order.text,crud_purchase.text))

        target.add_widget(crud_code)
        target.add_widget(crud_name)
        target.add_widget(crud_stock)
        #target.add_widget(crud_price)
        target.add_widget(crud_sold)
        target.add_widget(crud_order)
        target.add_widget(crud_purchase)
        target.add_widget(crud_submit)


    def update_user(self, name,user,pwd,des):

        pwd = hashlib.sha256(pwd.encode()).hexdigest()
        if user == '':
            self.notify.add_widget(Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch,1)
        else:
            user = self.users.find_one({'username':user})
            if user == None:
                self.notify.add_widget(Label(text='[color=#FF0000][b]Invalid Username[/b][/color]',markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch,1)
            else:
                if name == '':
                    name = user['name']
                if pwd == '':
                    pwd = user['password']
                self.users.update_one({'username':user},{'$set':{'name':name,'username':user,'password':pwd,'designation':des,'date':datetime.now()}})
                content = self.ids.scrn_contents
                content.clear_widgets()

                users = self.get_users()
                users_table = DataTable(table=users)
                content.add_widget(users_table)

    def update_product(self,code,name,stock,sold,order,purchase):

        if code == '':
            self.notify.add_widget(Label(text='[color=#FF0000][b]Code required[/b][/color]',markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch,1)
        else:
            target_code = self.products.find_one({'product_code':code})
            if target_code == None:
                self.notify.add_widget(Label(text='[color=#FF0000][b]Invalid Code[/b][/color]',markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch,1)
            else:
                if name == '':
                    name = target_code['product_name']
                if stock == '':
                    stock = target_code['in_stock']
                if sold == '':
                    sold = target_code['sold']
                if order == '':
                    order = target_code['order']
                if purchase == '':
                    purchase = target_code['last_purchase']
                content = self.ids.scrn_product_contents
                content.clear_widgets()

                self.products.update_one({'product_code':code},{'$set':{'product_code':code,'product_name':name,'in_stock':stock,'sold':sold,'order':order,'last_purchase':purchase}})

                products = self.get_products()
                stock_table = DataTable(table=products)
                content.add_widget(stock_table)

    def remove_user_fields(self):
        target = self.ids.ops_fields
        target.clear_widgets()
        crud_user = TextInput(hint_text='Username')
        crud_submit = Button(text='Remove',size_hint_x=None,width=100,on_release=lambda x: self.remove_user(crud_user.text))

        target.add_widget(crud_user)
        target.add_widget(crud_submit)

    def remove_client_fields(self):
        target = self.ids.ops_fields_c
        target.clear_widgets()
        crud_name = TextInput(hint_text='Name')
        crud_submit = Button(text='Remove',size_hint_x=None,width=100,on_release=lambda x: self.remove_user(crud_name.text))

        target.add_widget(crud_name)
        target.add_widget(crud_submit)

    def remove_product_fields(self):
        target = self.ids.ops_fields_p
        target.clear_widgets()
        crud_code = TextInput(hint_text='Product Code')
        crud_submit = Button(text='Remove',size_hint_x=None,width=100,on_release=lambda x: self.remove_product(crud_code.text))

        target.add_widget(crud_code)
        target.add_widget(crud_submit)

    def remove_user(self,user):

        if user == '':
            self.notify.add_widget(Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch,1)
        else:
            target_user = self.users.find_one({'username':user})
            if target_user == None:
                self.notify.add_widget(Label(text='[color=#FF0000][b]Invalid UserName[/b][/color]',markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch,1)
            else:
                content = self.ids.scrn_contents
                content.clear_widgets()

                self.users.remove({'username':user})

                users = self.get_users()
                users_table = DataTable(table=users)
                content.add_widget(users_table)

    def remove_client(self,name):

        if name == '':
            self.notify.add_widget(Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch,1)
        else:
            target_name = self.clients.find_one({'name':name})
            if target_name == None:
                self.notify.add_widget(Label(text='[color=#FF0000][b]Invalid UserName[/b][/color]',markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch,1)
            else:
                content = self.ids.scrn_client_contents
                content.clear_widgets()

                self.clients.remove({'name':name})

                clients = self.get_clients()
                clients_table = DataTable(table=clients)
                content.add_widget(clients_table)

    def remove_product(self,code):
        if code == '':
            self.notify.add_widget(Label(text='[color=#FF0000][b]All Fields Required[/b][/color]',markup=True))
            self.notify.open()
            Clock.schedule_once(self.killswitch,1)
        else:
            target_code = self.products.find_one({'product_code':code})
            if target_code == None:
                self.notify.add_widget(Label(text='[color=#FF0000][b]Invalid Code[/b][/color]',markup=True))
                self.notify.open()
                Clock.schedule_once(self.killswitch,1)
            else:
                content = self.ids.scrn_product_contents
                content.clear_widgets()

                self.products.remove({'product_code':code})

                prodz = self.get_products()
                stock_table = DataTable(table=prodz)
                content.add_widget(stock_table)

    def get_users(self):
        mongoClient = MongoClient()
        db = mongoClient.consumini
        users = db.users
        _users = OrderedDict()
        _users['names'] = {}
        _users['usernames'] = {}
        _users['passwords'] = {}
        _users['designations'] = {}
        names = []
        usernames = []
        passwords = []
        designations = []
        for user in users.find():
            names.append(user['name'])
            usernames.append(user['username'])
            pwd = user['password']
            if len(pwd) > 10:
                pwd = pwd[:10] + '...'
            passwords.append(pwd)
            designations.append(user['designation'])
        # print(designations)
        users_length = len(names)
        idx = 0
        while idx < users_length:
            _users['names'][idx] = names[idx]
            _users['usernames'][idx] = usernames[idx]
            _users['passwords'][idx] = passwords[idx]
            _users['designations'][idx] = designations[idx]

            idx += 1

        return _users

    def get_clients(self):
        mongoClient = MongoClient()
        db = mongoClient.consumini
        clients = db.clients
        _clients = OrderedDict()
        _clients['names'] = {}
        _clients['births'] = {}
        _clients['genders'] = {}
        names = []
        births = []
        genders = []
        for client in clients.find():
            names.append(client['name'])
            births.append(client['birthdate'])
            genders.append(client['gender'])
            name = client['name']
            if len(name) > 15:
                name = name[:10] + '...'
        clients_length = len(names)
        idx = 0
        while idx < clients_length:
            _clients['names'][idx] = names[idx]
            _clients['births'][idx] = births[idx]
            _clients['genders'][idx] = genders[idx]

            idx += 1

        return _clients

    def get_products(self):
        mongoClient = MongoClient()
        db = mongoClient.consumini
        products = db.stocks
        _stocks = OrderedDict()
        _stocks['product_code'] = {}
        _stocks['product_name'] = {}
        _stocks['in_stock'] = {}
        _stocks['sold'] = {}
        _stocks['order'] = {}
        _stocks['last_purchase'] = {}

        product_code = []
        product_name = []
        in_stock = []
        sold = []
        order = []
        last_purchase = []

        for product in products.find():
            product_code.append(product['product_code'])
            name = product['product_name']
            if len(name) > 10:
                name = name[:10] + '...'
            product_name.append(name)
            in_stock.append(product['in_stock'])
            try:
                sold.append(product['sold'])
            except KeyError:
                sold.append('')
            try:
                order.append(product['order'])
            except KeyError:
                order.append('')
            try:
                last_purchase.append(product['last_purchase'])
            except KeyError:
                last_purchase.append('')
        # print(designations)
        products_length = len(product_code)
        idx = 0
        while idx < products_length:
            _stocks['product_code'][idx] = product_code[idx]
            _stocks['product_name'][idx] = product_name[idx]
            _stocks['in_stock'][idx] = in_stock[idx]
            _stocks['sold'][idx] = sold[idx]
            _stocks['order'][idx] = order[idx]
            _stocks['last_purchase'][idx] = last_purchase[idx]


            idx += 1

        return _stocks

    def view_stats(self):
        plt.cla()
        self.ids.analysis_res.clear_widgets()
        target_product = self.ids.target_product.text
        target = target_product[:target_product.find(' | ')]
        name = target_product[target_product.find(' | '):]       

        df = pd.read_csv('products_purchase.csv')
        purchases = []
        dates = []
        count = 0
        for x in range(len(df)):
            if str(df.Product_Code[x]) == target:
                purchases.append(df.Purchased[x])
                dates.append(count)
                count+=1
        plt.bar(dates,purchases,color='teal',label=name)
        plt.ylabel('Total Purchases')
        plt.xlabel('day')

        self.ids.analysis_res.add_widget(FCK(plt.gcf()))


    def change_screen(self, instance):
        if instance.text == 'Manage Products':
            self.ids.scrn_mngr.current = 'scrn_product_content'
        elif instance.text == 'Manage Users':
            self.ids.scrn_mngr.current = 'scrn_content'
        else:
            self.ids.scrn_mngr.current = 'scrn_client_content'


class AdminApp(App):
    def build(self):

        return AdminWindow()

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

这就是我得到的输出:

[INFO   ] [Logger      ] Record log in C:\Users\pedro\.kivy\logs\kivy_19-12-04_23.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.1.17
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.1.9     
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.1.12     
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.1.22     
[INFO   ] [Kivy        ] v1.11.1
[INFO   ] [Kivy        ] Installed at "C:\Users\pedro\AppData\Local\Programs\Python\Python37\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "C:\Users\pedro\AppData\Local\Programs\Python\Python37\python.exe"
[INFO   ] [Factory     ] 184 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version <b'4.4.0 - Build 20.19.15.4703'>
[INFO   ] [GL          ] OpenGL vendor <b'Intel'>
[INFO   ] [GL          ] OpenGL renderer <b'Intel(R) HD Graphics 5500'>
[INFO   ] [GL          ] OpenGL parsed version: 4, 4
[INFO   ] [GL          ] Shading version <b'4.40 - Build 20.19.15.4703'>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[WARNING] [Factory     ] Ignored class "FlatButton" re-declaration. Current -  module: None, cls: None, baseclass: ButtonBehavior+Label, filename: C:\Users\pedro\Desktop\api_02\admin\admin.kv. Ignored -  module: None, cls: None, baseclass: ButtonBehavior+Label, filename: C:\Users\pedro\Desktop\api_02\signin\signin.kv.
[WARNING] [Factory     ] Ignored class "FlatButton" re-declaration. Current -  module: None, cls: None, baseclass: ButtonBehavior+Label, filename: C:\Users\pedro\Desktop\api_02\admin\admin.kv. Ignored -  module: None, cls: None, baseclass: ButtonBehavior+Label, filename: C:\Users\pedro\Desktop\api_02\till_operator\operator.kv.
 Traceback (most recent call last):
   File "kivy\properties.pyx", line 860, in kivy.properties.ObservableDict.__getattr__
 KeyError: 'target_product'

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "c:/Users/pedro/Desktop/api_02/main.py", line 8, in <module>
     class MainWindow(BoxLayout):
   File "c:/Users/pedro/Desktop/api_02/main.py", line 10, in MainWindow
     admin_widget = AdminWindow()
   File "c:\Users\pedro\Desktop\api_02\admin\admin.py", line 51, in __init__
     self.ids.target_product.values = spinvals
   File "kivy\properties.pyx", line 863, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

是否需要显示其他文件? 很抱歉有语法错误,我是巴西人,所以我的英语不太好

0 个答案:

没有答案