Search code examples
python-3.xtkintereditdelete-row

How to edit information in tkinter


I'm trying to write a code to get the name, salary, and age and show it in a list. I want this code have the feature of deleteing and editing the information. But in this step I don't know how delete or edit a particular information.

from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *

i = 2
table_row = []
def getting():
        global i
        i = i + 1
        data = []
        var = IntVar()
        c = Checkbutton(window, variable=var)
        c.val = var
        data.append(c)
        c.grid(row=i, column=0)

        value1=e11.get()
        data.append(value1)
        value2 = e22.get()
        data.append(value2)
        value3 = e33.get()
        data.append(value3)

        lblq = Label(window, text=data[1:])
        lblq.grid(row=i, column=1)
        table_row.append(data)
        # print(table_row)

def delete_row():
    for Noo, row in reversed(list(enumerate(table_row))):
        if row[0].val.get() == 1:
            for i in row:
                i.destroy()
            table_row(Noo)

window = Tk()
window.title("Table with add, edit and delete")
window.geometry('600x600')

def Closing():
    res = messagebox.askokcancel("warning", "Are You sure!!!!!")
    if res == True:
        sys.exit()

    ############################################### #menu inside winodow
menu = Menu(window)

new_item = Menu(menu)

new_item.add_command(label="Exit", command=Closing)

menu.add_cascade(label='File', menu=new_item)

window.config(menu=menu)
###############################################
lblname =Label(window, text="Name")
lblname.place(x = 440,y = 130)
e11 = Entry(window, width=20)
e11.place(x = 440,y = 150)

lblsurname =Label(window, text="Salary")
lblsurname.place(x = 440,y = 180)
e22 = Entry(window, width=20)
e22.place(x = 440,y = 200)

lblage =Label(window, text="Age")
lblage.place(x = 440,y = 240)
e33 = Entry(window, width=20)
e33.place(x = 440,y = 260)

dl = Button(window, text='Delete',command=delete_row)
dl.place(x = 440,y = 10)

dl = Button(window, text='Edit')
dl.place(x = 440,y = 50)

B2 = Button(window, text="+ add emplyoee", command=getting)
B2.place(x = 440,y = 90)

v0 = StringVar()
e0 = Entry(window, textvariable=v0, state='readonly')
v0.set('Select')
e0.grid(row=1, column=0)

v1 = StringVar()
e1 = Entry(window, textvariable=v1, state='readonly')
v1.set('Information')
e1.grid(row=1, column=1)

window.mainloop()

Maybe I should use Class in my code, but I is difficult for me to use Class and tkinter simultaneously


Solution

  • You could use dictionary to keep single row - it would be more readable

    When I add row I create dictionary with widgets and text from Entry, I add to list of rows and clear Entry.

    If there is selected row in table then I don't create new row but replace text in selected row.

    The same way I search selected row to copy text from row to Entry.

    The same way I search selected row to remove row - destroy widgets and delete row on the list.

    It is more easier to do it because I use dictionary to keep row and it is more readable.

    from tkinter import *
    from tkinter import messagebox
    from tkinter.ttk import *
    
    # --- functions ---
    
    def closing():
        res = messagebox.askokcancel("warning", "Are You sure!!!!!")
        if res == True:
            sys.exit()
    
    def add_row():
        global row_number
    
        # check if there is selected row to update    
        update = None
        for row in table_row:
            if row['var'].get() == 1:
               update = row
               break # dont search next selected row
    
        if update:
            row['data'] = [e11.get(), e22.get(), e33.get()]
            row['label']['text'] = row['data']
        else:
            row_number += 1
    
            row = dict()
    
            row['row_number'] = row_number
    
            row['var'] = IntVar()
    
            row['checkbutton'] = Checkbutton(window, variable=row['var'])
            row['checkbutton'].grid(row=row_number, column=0)
    
            row['data'] = [e11.get(), e22.get(), e33.get()]
    
            row['label'] = Label(window, text=row['data'])
            row['label'].grid(row=row_number, column=1)
    
            table_row.append(row)
    
        # clear entry 
        e11.delete('0', 'end')
        e22.delete('0', 'end')
        e33.delete('0', 'end')
        lblnumber["text"] = "Row number: -"
    
    def delete_row():
        for row in reversed(table_row):
            if row['var'].get() == 1:
                # remove widgets
                row['checkbutton'].destroy()
                row['label'].destroy()
                # remove row from list
                del row
    
    def edit_row():
        for row in table_row:
            if row['var'].get() == 1:
                # remove all text
                e11.delete('0', 'end')
                e22.delete('0', 'end')
                e33.delete('0', 'end')
                # put text from row
                e11.insert('end', row['data'][0])
                e22.insert('end', row['data'][1])
                e33.insert('end', row['data'][2])
                lblnumber["text"] = "Row number: {}".format(row['row_number'])
                break # dont search next selected row
    
    # --- main ---
    
    row_number = 2
    table_row = []
    
    window = Tk()
    window.title("Table with add, edit and delete")
    window.geometry('600x600')
    
    menu = Menu(window)
    new_item = Menu(menu)
    new_item.add_command(label="Exit", command=closing)
    menu.add_cascade(label='File', menu=new_item)
    window.config(menu=menu)
    
    lblnumber = Label(window, text="Row Number: -")
    lblnumber.place(x=440, y=330)
    
    e00 = Label(window, width=20)
    e00.place(x=440, y=150)
    
    lblname = Label(window, text="Name")
    lblname.place(x=440, y=130)
    
    e11 = Entry(window, width=20)
    e11.place(x=440, y=150)
    
    lblsurname = Label(window, text="Salary")
    lblsurname.place(x=440, y=180)
    
    e22 = Entry(window, width=20)
    e22.place(x=440, y=200)
    
    lblage = Label(window, text="Age")
    lblage.place(x=440, y=240)
    
    e33 = Entry(window, width=20)
    e33.place(x=440, y=260)
    
    dl = Button(window, text='Delete', command=delete_row)
    dl.place(x=440, y=10)
    
    dl = Button(window, text='Edit', command=edit_row)
    dl.place(x=440, y=50)
    
    B2 = Button(window, text="+ add emplyoee", command=add_row)
    B2.place(x=440, y=90)
    
    v0 = StringVar()
    e0 = Entry(window, textvariable=v0, state='readonly')
    v0.set('Select')
    e0.grid(row=1, column=0)
    
    v1 = StringVar()
    e1 = Entry(window, textvariable=v1, state='readonly')
    v1.set('Information')
    e1.grid(row=1, column=1)
    
    window.mainloop()