Как исправить ошибку tuple index out of range?

Я пытаюсь сделать простой GUI с базой данных, но появилась ошибка

tuple index out of range

при попытке редактировать запись функцией update_record.
Помогите пожалуйста!

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(data=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)

    self.btn_edit_dialog_img = tk.PhotoImage(data=edit_gif)
    btn_edit_dialog = tk.Button(toolbar, text='Редактировать', command=self.open_update_dialog, bg='#d7d8e0', bd=0,
                                compound=tk.TOP, image=self.btn_edit_dialog_img)
    btn_edit_dialog.pack(side=tk.LEFT)

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

    self.tree.column('description', anchor=tk.CENTER, width=630)

    self.tree.heading('description', text='Объект закупки')

    self.tree.pack()

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

def update_record(self, description):
    self.db.c.execute('''UPDATE Dealers SET description=? WHERE id=?''',
                      (description, self.tree.set(self.tree.selection()[0], '#1')))
    print(description)
    self.db.conn.commit()
    self.view_records()

def view_records(self):
    self.db.c.execute('''SELECT description FROM Dealers''')
    [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.init_child()
        self.view = app

def init_child(self):
    self.title('Добавить объект закупки')
    self.geometry('400x120+400+300')
    self.resizable(False, False)

    label_description = tk.Label(self, text='Объект закупки')
    label_description.place(x=50, y=50)

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

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

    self.btn_ok = ttk.Button(self, text='Добавить')
    self.btn_ok.place(x=220, y=80)
    self.btn_ok.bind('<Button-1>', lambda event: self.view.records(self.entry_description.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=80)
    btn_edit.bind('<Button-1>', lambda event: self.view.update_record(self.entry_description.get()))

    self.btn_ok.destroy()


class DB:
    def __init__(self):
        self.conn = sqlite3.connect('Dealers.db')
        self.c = self.conn.cursor()
        self.c.execute(
            '''CREATE TABLE IF NOT EXISTS Dealers (id integer primary key, description text)''')
        self.conn.commit()

def insert_data(self, description):
    self.c.execute('''INSERT INTO Dealers(description) VALUES (?)''',
                   (description,))
    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()

Ниже текст ошибки

 Exception in Tkinter callback
    Traceback (most recent call last):
      File "C:\Users\311\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
        return self.func(*args)
      File "C:/Users/Public/LAN обменник/URFU/Postavshiki/Les2.py", line 133, in <lambda>
        btn_edit.bind('<Button-1>', lambda event: self.view.update_record(self.entry_description.get()))
      File "C:/Users/Public/LAN обменник/URFU/Postavshiki/Les2.py", line 75, in update_record
        (description, self.tree.set(self.tree.selection()[0], '#1')))
    IndexError: tuple index out of range

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

Автор решения: S. Nick

Попробуйте так:

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(data=add_gif)
        self.add_img = tk.PhotoImage(file="Ok.png")

        
        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)

#        self.btn_edit_dialog_img = tk.PhotoImage(data=edit_gif)
        self.btn_edit_dialog_img = tk.PhotoImage(file="ball.png")        
        
        btn_edit_dialog = tk.Button(toolbar, text='Редактировать', command=self.open_update_dialog, bg='#d7d8e0', bd=0,
                                    compound=tk.TOP, image=self.btn_edit_dialog_img)
        btn_edit_dialog.pack(side=tk.LEFT)

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

        self.tree.column('description', anchor=tk.CENTER, width=630)
        self.tree.heading('description', text='Объект закупки')
        self.tree.pack()

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

# !!! 
    def update_record(self, description):
        print(f'{self.tree.selection()}')                           #
        if not self.tree.selection():                               # +++
            print(f'Выберите строку для редактирования')            # +++
            return                                                  # +++
        
        self.db.c.execute('''UPDATE Dealers SET description=? WHERE id=?''',
                          (description, self.tree.set(self.tree.selection()[0], '#1')))
        print(description)
        self.db.conn.commit()
        self.view_records()

    def view_records(self):
        self.db.c.execute('''SELECT description FROM Dealers''')
        [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.init_child()
        self.view = app

    def init_child(self):
        self.title('Добавить объект закупки')
        self.geometry('400x120+400+300')
        self.resizable(False, False)

        label_description = tk.Label(self, text='Объект закупки')
        label_description.place(x=50, y=50)

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

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

        self.btn_ok = ttk.Button(self, text='Добавить')
        self.btn_ok.place(x=220, y=80)
        self.btn_ok.bind('<Button-1>', lambda event: self.view.records(self.entry_description.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=80)
        btn_edit.bind('<Button-1>', lambda event: self.view.update_record(self.entry_description.get()))

        self.btn_ok.destroy()


class DB:
    def __init__(self):
        self.conn = sqlite3.connect('Dealers.db')
        self.c = self.conn.cursor()
        self.c.execute(
            '''CREATE TABLE IF NOT EXISTS Dealers (id integer primary key, description text)''')
        self.conn.commit()

    def insert_data(self, description):
        self.c.execute('''INSERT INTO Dealers(description) VALUES (?)''',
                       (description,))
        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()

введите сюда описание изображения

введите сюда описание изображения

→ Ссылка