Как производить несколько поисков по разным полям базы? Ошибка в коде self.view = app NameError: name 'app' is not defined В чем проблема?

import tkinter as tk from tkinter import ttk import sqlite3

Класс Main

class Main(tk.Frame): def init(self, root): super().init(root) self.init_main() self.db = db self.view_records()

Главное окно

def init_main(self): toolbar = tk.Frame(bg='beige', bd=2) toolbar.pack(side=tk.TOP, fill=tk.X)

        self.add_img = tk.PhotoImage(file='add.png')
        btn_open_dialog = tk.Button(toolbar, text='Добавить техники или ПО ', command=self.open_dialog, bg='beige',
                                    bd=0, compound=tk.TOP, image=self.add_img)
        btn_open_dialog.pack(side=tk.LEFT)

        self.update_img = tk.PhotoImage(file='edit.png')
        btn_edit_dialog = tk.Button(toolbar, text='Редактировать элементы', bg='beige', bd=0, image=self.update_img,
                                    compound=tk.TOP, command=self.open_update_dialog)
        btn_edit_dialog.pack(side=tk.LEFT)

        self.delete_img = tk.PhotoImage(file='delete.png')
        btn_delete_dialog = tk.Button(toolbar, text='Удалить', bg='beige', bd=0, image=self.delete_img,
                                      compound=tk.TOP, command=self.delete_records)
        btn_delete_dialog.pack(side=tk.LEFT)

# Меню для поиска по наименованиям
        self.search_img_name = tk.PhotoImage(file='search.png')
        btn_search_name = tk.Button(toolbar, text='Поиск по наименованиям', bg='beige', bd=0, image=self.search_img_name,
                               compound=tk.TOP, command=self.open_search_dialog_name())

        btn_search_name.pack(side=tk.LEFT)

# Меню для поиска по категориям
        self.search_img_categ = tk.PhotoImage(file='search.png')
        btn_search_categ = tk.Button(toolbar, text='Поиск по категориям', bg='beige', bd=0, image=self.search_img_categ,
                               compound=tk.TOP, command=self.open_search_dialog_categ())

        btn_search_categ.pack(side=tk.LEFT)

        self.refresh_img = tk.PhotoImage(file='refresh.png')
        btn_refresh = tk.Button(toolbar, text='Обновить', bg='beige', bd=0, image=self.refresh_img,
                                compound=tk.TOP, command=self.view_records)
        btn_refresh.pack(side=tk.LEFT)

        self.tree = ttk.Treeview(self, columns=('ID', 'description', 'category', 'price','count', 'auditory'), height=15, show='headings')

        self.tree.column('ID', width=30, anchor=tk.CENTER)
        self.tree.column('description', width=265, anchor=tk.CENTER)
        self.tree.column('category', width=150, anchor=tk.CENTER)
        self.tree.column('price', width=100, anchor=tk.CENTER)
        self.tree.column('count', width=100, anchor=tk.CENTER)
        self.tree.column('auditory', width=100, anchor=tk.CENTER)

        self.tree.heading('ID', text='ID')
        self.tree.heading('description', text='Наименование')
        self.tree.heading('category', text='Категория')
        self.tree.heading('price', text='Цена')
        self.tree.heading('count', text='Количество')
        self.tree.heading('auditory', text='Аудитория')

        self.tree.pack(side=tk.LEFT)

        scroll = tk.Scrollbar(self, command=self.tree.yview)
        scroll.pack(side=tk.LEFT, fill=tk.Y)
        self.tree.configure(yscrollcommand=scroll.set)

# Добавление данных
    def records(self, description, category, price, count, auditory):
        self.db.insert_data(description, category, price, count, auditory)
        self.view_records()

# Обновление данных
    def update_record(self, description, category, price, count, auditory):
        self.db.c.execute('''UPDATE accounting  SET description=?, category=?, price=?, count=?, auditory=? WHERE ID=?''',
                          (description, category, price, count, auditory, self.tree.set(self.tree.selection()[0], '#1')))
        self.db.conn.commit()
        self.view_records()

# Вывод данных
    def view_records(self):
        self.db.c.execute('''SELECT * FROM accounting''')
        [self.tree.delete(i) for i in self.tree.get_children()]
        [self.tree.insert('', 'end', values=row) for row in self.db.c.fetchall()]

# Удаление данных
    def delete_records(self):
        for selection_item in self.tree.selection():
            self.db.c.execute('''DELETE FROM accounting WHERE id=? ''', (self.tree.set(selection_item, '#1'),))
            self.db.conn.commit()
            self.view_records()

# Поиск данных по наименованиям
    def search_records_desc(self, description):
        description = ('%' + description + '%',)
        self.db.c.execute('''SELECT * FROM accounting WHERE description LIKE ?''', description)
        [self.tree.delete(i) for i in self.tree.get_children()]
        [self.tree.insert('', 'end', values=row) for row in self.db.c.fetchall()]

# Поиск данных по категориям
    def search_records_categ(self, category):
        category = ('%' + category + '%',)
        self.db.c.execute('''SELECT * FROM accounting WHERE category LIKE ?''', category)
        [self.tree.delete(i) for i in self.tree.get_children()]
        [self.tree.insert('', 'end', values=row) for row in self.db.c.fetchall()]

    def search_records(self, auditory):
        auditory = ('%' + auditory + '%',)
        self.db.c.execute('''SELECT * FROM accounting WHERE auditory LIKE ?''', auditory)
        [self.tree.delete(i) for i in self.tree.get_children()]
        [self.tree.insert('', 'end', values=row) for row in self.db.c.fetchall()]

# Открытие дочернего окна
    def open_dialog(self):
        Child()

    def open_update_dialog(self):
        Update()

    def open_search_dialog_name(self):
        Search_name()

    def open_search_dialog_categ(self):
        Search_categ()

# Дочернее окно
class Child(tk.Toplevel):
    def __init__(self):
        super().__init__(root)
        self.init_child()
        self.view = app

    def init_child(self):
        self.title('Добавить техники')
        self.geometry('400x320+400+300')
        self.resizable(False, False)

        label_description = tk.Label(self, text='Наименование')
        label_description.place(x=50, y=50)

        label_select = tk.Label(self, text='Категория')
        label_select.place(x=50, y=80)

        label_price = tk.Label(self, text='Цена: ')
        label_price.place(x=50, y=110)

        label_price = tk.Label(self, text='Количество: ')
        label_price.place(x=50, y=140)

        label_price = tk.Label(self, text='Аудитория: ')
        label_price.place(x=50, y=170)

        self.entry_description = ttk.Entry(self)
        self.entry_description.place(x=200, y=50)

        self.entry_money = ttk.Entry(self)
        self.entry_money.place(x=200, y=110)

        self.entry_count = ttk.Entry(self)
        self.entry_count.place(x=200, y=140)

        self.entry_auditory = ttk.Entry(self)
        self.entry_auditory.place(x=200, y=170)

        self.combobox = ttk.Combobox(self, values=[u'Процессор', u'Монитор', u'Видеокарта', u'Оперативная память',
                                                   u'Материнская плата', u'Операционная система', u'Программа',u'Планшеты', 'Ноутбуки'])
        self.combobox.current(0)
        self.combobox.place(x=200, y=80)

        btn_cancel = ttk.Button(self, text='Закрыть', command=self.destroy)
        btn_cancel.place(x=300, y=220)

        self.btn_ok = ttk.Button(self, text='Добавить')
        self.btn_ok.place(x=220, y=220)
        self.btn_ok.bind('<Button-1>', lambda event: self.view.records(self.entry_description.get(),
                                                                       self.combobox.get(),
                                                                       self.entry_money.get(),
                                                                       self.entry_count.get(),
                                                                       self.entry_auditory.get()))

        self.grab_set()
        self.focus_set()


# Класс обновления унаследованный от дочернего окна
class Update(Child):
    def __init__(self):
        super().__init__()
        self.init_edit()
        self.view = app
        self.db = db
        self.default_data()


    def init_edit(self):
        self.title('Редактировать')
        btn_edit = ttk.Button(self, text='Редактировать')
        btn_edit.place(x=205, y=220)
        btn_edit.bind('<Button-1>', lambda event: self.view.update_record(self.entry_description.get(),
                                                                          self.combobox.get(),
                                                                          self.entry_money.get(),
                                                                          self.entry_count.get(),
                                                                          self.entry_auditory.get()))
        self.btn_ok.destroy()


    def default_data(self):
        self.db.c.execute('''SELECT * FROM accounting WHERE id=?''',
                          (self.view.tree.set(self.view.tree.selection()[0], '#1'),))
        row = self.db.c.fetchone()
        self.entry_description.insert(0, row[1])
        if row[2] != 'Процессор':
            self.combobox.current(1)
        self.entry_money.insert(0, row[3])
        self.entry_count.insert(0, row[4])
        self.entry_auditory.insert(0, row[5])


# Поиск по наименованию
class Search_name(tk.Toplevel):
    def __init__(self):
        super().__init__()
        self.init_search_name()
        self.view = app
        self.db = db                        ##These two lines were got in
        self.default_data()



#  Дочернее окно для поиска по названиям
    def init_search_name(self):
        self.title('Поиск по названиям')
        self.geometry('300x100+400+300')
        self.resizable(False, False)

        label_search = tk.Label(self, text='Поиск')
        label_search.place(x=50, y=20)

        self.entry_search = ttk.Entry(self)
        self.entry_search.place(x=105, y=20, width=150)

        btn_cancel = ttk.Button(self, text='Закрыть', command=self.destroy)
        btn_cancel.place(x=185, y=50)

        btn_search = ttk.Button(self, text='Поиск')
        btn_search.place(x=105, y=50)

        btn_search.bind('<Button-1>', lambda event: self.view.search_records_desc(self.entry_search.get()))
        btn_search.bind('<Button-1>', lambda event: self.destroy(), add='+')

class Search_categ(tk.Toplevel):
        def __init__(self):
            super().__init__()
            self.init_search_categ()
            self.view = app

#  Дочернее окно для поиска по категориям
        def init_search_categ(self):
            self.title('Поиск по категориям')
            self.geometry('300x100+400+300')
            self.resizable(False, False)

            label_search = tk.Label(self, text='Поиск')
            label_search.place(x=50, y=20)

            self.entry_search = ttk.Entry(self)
            self.entry_search.place(x=105, y=20, width=150)

            btn_cancel = ttk.Button(self, text='Закрыть', command=self.destroy)
            btn_cancel.place(x=185, y=50)

            btn_search = ttk.Button(self, text='Поиск')
            btn_search.place(x=105, y=50)

            btn_search.bind('<Button-1>', lambda event: self.view.search_records_categ(self.entry_search.get()))
            btn_search.bind('<Button-1>', lambda event: self.destroy(), add='+')

# Создание базы данных
class DB:
    def __init__(self):
        self.conn = sqlite3.connect('accounting.db')
        self.c = self.conn.cursor()
        self.c.execute(
            '''CREATE TABLE IF NOT EXISTS accounting (id integer primary key,description text, 
            category text, price real,count integer, auditory text)''')
        self.conn.commit()

    def insert_data(self, description, category, price, count, auditory):
        self.c.execute('''INSERT INTO accounting (description, category, price, count, auditory) VALUES (?, ?, ?, ?, ?) ''',
                       (description, category, price, count, auditory))
        self.conn.commit()


# Основной код для запуска
if __name__ == "__main__":
    root = tk.Tk()
    db = DB()
    app = Main(root)
    app.pack()
    root.title("Учет компьютерной техники")
    root.geometry("865x450+300+200")
    root.resizable(False, False)
    root.mainloop()

Ответы (0 шт):