Здравствуйте столкнулся с проблемой, Tkinter, Sqlite3, Ttk, пишет что name 'app' is not defined

вот весь код

import tkinter as tk
from tkinter import ttk
import sqlite3

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='#d7d8e0', bd=2)
        toolbar.pack(side=tk.TOP, fill=tk.X)

        self.add_img = tk.PhotoImage(file='directory_kotik/icons8.gif')

        btn_open_dialog = tk.Button(toolbar, text="Добавить позицию",  image=self.add_img, command=self.open_dialog(), bd=0,
                                    compound=tk.TOP)

        btn_open_dialog.pack(side=tk.LEFT)

        self.tree = ttk.Treeview(self, columns=('ID', 'description', 'costs', 'total'), height=15, show='headings')

        self.tree.column('ID', width=30, anchor=tk.CENTER)
        self.tree.column('description', width=360, anchor=tk.CENTER)
        self.tree.column('costs', width=150, anchor=tk.CENTER)
        self.tree.column('total', width=100, anchor=tk.CENTER)

        self.tree.heading('ID', text='ID')
        self.tree.heading('description', text='Наименования')
        self.tree.heading('costs', text='Статья расхода/дохода')
        self.tree.heading('total', text='Сумма')

        self.tree.pack()

    def records(self, description, costs, total):
        self.db.insert_data(description, costs, total)
        self.view_records()

    def view_records(self):
        self.db.cur.execute('''SELECT * FROM finance''')
        [self.tree.delete(i) for i in self.tree.get_children()]
        [self.tree.insert('', 'end', values=row) for row in self.db.cur.fetchall()]
    def open_dialog(self):
        Child()

class Child(tk.Toplevel):
    def __init__(self):
        super().__init__(root)
        self.init_child()
        self.view = app

    def init_child(self):
        self.title('Добавить расходы\доходы')
        self.geometry('400x220+400+300')
        self.resizable(False, False)

        label_description = tk.Label(self, text='Наименование:')
        label_description.place(x=50, y=50)
        label_selection = tk.Label(self, text='Статья расхода/дохода:')
        label_selection.place(x=50, y=80)
        label_sum = tk.Label(self, text='Сумма:')
        label_sum.place(x=50, y=110)

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

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

        self.combobox = ttk.Combobox(self, values=[u'Доход', u'Расход'])
        self.combobox.current(0)
        self.combobox.place(x=200, y=80)

        btn_cancel = tk.Button(self, text='Закрыть', command=self.destroy)
        btn_cancel.place(x=300, y=170)
        btn_add = ttk.Button(self, text='Добавить')
        btn_add.place(x=220, y=170)
        btn_add.bind('<Button-1>', lambda event: self.view.records(self.entry_description.get(),
                                                                   self.combobox.get(),
                                                                   self.entry_money.get()))
        self.grab_set()
        self.focus_set()

class DB:
    def __init__(self):
        self.conn = sqlite3.connect('finance.db')
        self.cur = self.conn.cursor()
        self.cur.execute(
            '''CREATE TABLE IF NOT EXISTS finance (id integer primary key, description text, costs text, total real)''')
        self.conn.commit()
    def insert_data(self, description, costs, total):
        self.cur.execute('''INSERT INTO finance (description, costs, total) VALUES (?, ?, ?)''',
                         (description, costs, total))
        self.conn.commit()

if __name__ == "__main__":
    root = tk.Tk()
    db = DB()
    app = Main(root)
    app.pack()
    root.title("Household finance")
    root.geometry("650x450+300+200")
    root.resizable(False, False)
    root.mainloop()

Вот ошибка которую мне выдает, не понимаю в чем проблема, вроде все верно

Traceback (most recent call last):
  File "C:\Users\Алексей\PycharmProjects\AI_Assistent\main.py", line 100, in <module>
    app = Main(root)
          ^^^^^^^^^^
  File "C:\Users\Алексей\PycharmProjects\AI_Assistent\main.py", line 8, in __init__
    self.init_main()
  File "C:\Users\Алексей\PycharmProjects\AI_Assistent\main.py", line 18, in init_main
    btn_open_dialog = tk.Button(toolbar, text="Добавить позицию",  image=self.add_img, command=self.open_dialog(), bd=0,
                                                                                               ^^^^^^^^^^^^^^^^^^
  File "C:\Users\Алексей\PycharmProjects\AI_Assistent\main.py", line 46, in open_dialog
    Child()
  File "C:\Users\Алексей\PycharmProjects\AI_Assistent\main.py", line 52, in __init__
    self.view = app
                ^^^
NameError: name 'app' is not defined

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

Автор решения: insolor

Так у вас Child создается раньше, чем переменная app инициализирована. app у вас - это объект Main, передавайте его внутрь Child при его создании как параметр.

class Main(tk.Frame):
   ...

   def open_dialog(self):
       Child(self)

...


class Child(tk.Toplevel):
    def __init__(self, app):
        super().__init__(root)
        self.init_child()
        self.view = app

root я бы тоже передавал через параметры, чтобы класс Child не зависел от глобальных переменных.

→ Ссылка