Форум сайта python.su
0
Собственно задача стоит в том, чтоб организовать функцию редактирования ранее добавленных полей в базу данных из соответствующего окна, по нажатию кнопки “Редактировать” (иконку ещё не нарисовал).
Другими словами: в таблице выделяю поле, затем нажимаю кнопку редактировать, изменяю необходимые записи, а далее внесенные изменения сохраняются в БД и обновляются в таблице.
Сейчас вылетает ошибка, где я накосячил? Как исправить? В чем ошибка?
import tkinter as tk from tkinter import ttk import sqlite3 class Main(tk.Frame): def __init__(self, root): super().__init__(root) self.db = db self.init_main() 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="add.gif") btn_open_dialog = tk.Button(toolbar, text='Добавить позицию', command=self.open_dialog, bg='#d7d8e0', bd=0, compound=tk.TOP, image=self.add_img) btn_open_dialog.pack(side=tk.LEFT) btn_edit_dialog = tk.Button(toolbar, text='Редактировать', command=self.open_update_dialog, bg='#d7d8e0', bd=0, compound=tk.TOP, image=self.add_img) btn_edit_dialog.pack(side=tk.LEFT) self.tree = ttk.Treeview(self, columns=('ID', 'description', 'costs', 'total', 'date'), 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("costs", width=150, anchor=tk.CENTER) self.tree.column("total", width=100, anchor=tk.CENTER) self.tree.column("date", 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.heading("date", text='Дата') self.tree.pack() def records(self, description, coasts, total): self.db.insert_data(description, coasts, total) self.view_records() def update_record(self, description, coasts, total): self.db.update_data(description, coasts, total) self.view_records() def view_records(self): self.db.c.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.c.fetchall()] def open_dialog(self): Child() def open_update_dialog(self): Update() class Child(tk.Toplevel): def __init__(self): super().__init__(root) self.view = app self.init_child() 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_select = tk.Label(self, text='Статья дохода/расхода:') label_select.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=200, y=50) self.entry_money = ttk.Entry(self) self.entry_money.place(x=200, y=110) self.combobox = ttk.Combobox(self, values=[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=170) self.btn_ok = ttk.Button(self, text='Добавить') self.btn_ok.place(x=220, y=170) self.btn_ok.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 Update(Child): def __init__(self): super().__init__() self.init_edit() self.view = app def init_edit(self): self.title('Редактировать позицию') btn_edit = ttk.Button(self, text='Редактировать') btn_edit.place(x=205, y=170) btn_edit.bind('<Button-1>', lambda event: self.view.update_record(self.entry_description.get(), self.combobox.get(), self.entry_money.get())) self.btn_ok.destroy() class DB: def __init__(self): self.view = app self.conn = sqlite3.connect('finance.db') self.c = self.conn.cursor() self.c.execute( '''CREATE TABLE IF NOT EXISTS finance (id integer primary key, description text, costs text, total real, date text)''') self.conn.commit() def insert_data(self, description, costs, total): self.c.execute('''INSERT INTO finance(description, costs, total) VALUES (?, ?, ?)''', (description, costs, total)) self.conn.commit() def update_data(self, description, costs, total): for selected_item in self.view.tree.selection(): self.c.execute("UPDATE profile SET description=?, costs=?, total=? WHERE ID =?", (description, costs, total, self.view.tree.set(selected_item, '#1'))) self.conn.commit() if __name__ == "__main__": root = tk.Tk() db = DB() app = Main(root) app.pack() root.title("Домашние финансы") root.geometry("650x450+300+200") root.resizable(False, False) root.mainloop()
Прикреплённый файлы:
add.gif (547 байт)
Офлайн
72
Нужно перенести обновление базы из класса DB в класс Main, пояснения в коде:
1. class Main, def update_record
2. class DB, def update_data
import tkinter as tk from tkinter import ttk import sqlite3 class Main(tk.Frame): def __init__(self, root): super().__init__(root) self.db = db self.init_main() 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="add.gif") btn_open_dialog = tk.Button(toolbar, text='Добавить позицию', command=self.open_dialog, bg='#d7d8e0', bd=0, compound=tk.TOP, image=self.add_img) btn_open_dialog.pack(side=tk.LEFT) btn_edit_dialog = tk.Button(toolbar, text='Редактировать', command=self.open_update_dialog, bg='#d7d8e0', bd=0, compound=tk.TOP, image=self.add_img) btn_edit_dialog.pack(side=tk.LEFT) self.tree = ttk.Treeview(self, columns=('ID', 'description', 'costs', 'total', 'date'), 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("costs", width=150, anchor=tk.CENTER) self.tree.column("total", width=100, anchor=tk.CENTER) self.tree.column("date", 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.heading("date", text='Дата') self.tree.pack() def records(self, description, coasts, total): self.db.insert_data(description, coasts, total) self.view_records() def update_record(self, description, coasts, total): """Обновляем базу прямо здесь, а не в классе DB""" for selected_item in self.tree.selection(): db.c.execute("UPDATE finance SET description=?, costs=?, total=? WHERE ID =?", (description, coasts, total, self.tree.set(selected_item, '#1'))) db.conn.commit() # self.db.update_data(description, coasts, total) #Это убрать: обновлять нужно здесь, а не в классе DB self.view_records() def view_records(self): self.db.c.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.c.fetchall()] def open_dialog(self): Child() def open_update_dialog(self): Update() class Child(tk.Toplevel): def __init__(self): super().__init__(root) self.view = app self.init_child() 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_select = tk.Label(self, text='Статья дохода/расхода:') label_select.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=200, y=50) self.entry_money = ttk.Entry(self) self.entry_money.place(x=200, y=110) self.combobox = ttk.Combobox(self, values=[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=170) self.btn_ok = ttk.Button(self, text='Добавить') self.btn_ok.place(x=220, y=170) self.btn_ok.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 Update(Child): def __init__(self): super().__init__() self.init_edit() self.view = app def init_edit(self): self.title('Редактировать позицию') btn_edit = ttk.Button(self, text='Редактировать') btn_edit.place(x=205, y=170) btn_edit.bind('<Button-1>', lambda event: self.view.update_record(self.entry_description.get(), self.combobox.get(), self.entry_money.get())) self.btn_ok.destroy() class DB: def __init__(self): # self.view = app #Это убрать!!! self.conn = sqlite3.connect('finance.db') self.c = self.conn.cursor() self.c.execute( '''CREATE TABLE IF NOT EXISTS finance (id integer primary key, description text, costs text, total real, date text)''') self.conn.commit() def insert_data(self, description, costs, total): self.c.execute('''INSERT INTO finance(description, costs, total) VALUES (?, ?, ?)''', (description, costs, total)) self.conn.commit() ''' Это убрать!!! def update_data(self, description, costs, total): # for selected_item in self.view.tree.selection(): self.c.execute("UPDATE profile SET description=?, costs=?, total=? WHERE ID =?", (description, costs, total, self.view.tree.set(selected_item, '#1'))) self.conn.commit() ''' if __name__ == "__main__": root = tk.Tk() db = DB() app = Main(root) app.pack() root.title("Домашние финансы") root.geometry("650x450+300+200") root.resizable(False, False) root.mainloop()
Офлайн
0
rami
Ну да, логично)
Спасибо огромное)
Офлайн