Python Tkinter Treeview Add Row

 How To Insert a Row to a tkinter treeview (Table) using python

Python Tkinter Treeview Add Row


import tkinter as tk
from tkinter import *
from tkinter import ttk


root = Tk()
frame = tk.Frame(root, bg='#3498db')
frame_btns = tk.Frame(frame, bg='#3498db')

data = [
[1,"AAA","BBB","ab@mail.com",17],
[3,"EEE","FFF","ef@mail.com",91],
[4,"GGG","HHH","gh@mail.com",47],
[7,"MMM","NNN","mn@mail.com",25],
[8,"PPP","QQQ","pq@mail.com",43],
[9,"RRR","SSS","rs@mail.com",94],
]

label_id = tk.Label(frame, text='ID:', font=('verdana',14), bg='#3498db')
entry_id = tk.Entry(frame, font=('verdana',14))

label_fname = tk.Label(frame, text='First Name:', font=('verdana',14), bg='#3498db')
entry_fname = tk.Entry(frame, font=('verdana',14))

label_lname = tk.Label(frame, text='Last Name:', font=('verdana',14), bg='#3498db')
entry_lname = tk.Entry(frame, font=('verdana',14))

label_email = tk.Label(frame, text='Email:', font=('verdana',14), bg='#3498db')
entry_email = tk.Entry(frame, font=('verdana',14))

label_age = tk.Label(frame, text='Age:', font=('verdana',14), bg='#3498db')
entry_age = tk.Entry(frame, font=('verdana',14))

btn_add = tk.Button(frame, text='Add', font=('verdana',14), bg='#f39c12',
fg='#ffffff', width=10)

trv = ttk.Treeview(frame, columns=(1,2,3,4,5), show='headings')
trv.column(1, anchor='center', width=100)
trv.column(2, anchor='center', width=100)
trv.column(3, anchor='center', width=100)
trv.column(4, anchor='center', width=100)
trv.column(5, anchor='center', width=100)

trv.heading(1, text='ID')
trv.heading(2, text='First Name')
trv.heading(3, text='Last Name')
trv.heading(4, text='Email')
trv.heading(5, text='Age')

# create a function to display data in treeview
def displayData():
for row in data:
trv.insert('',END, values=row)


displayData()



def add():
user_id = entry_id.get()
fname = entry_fname.get()
lname = entry_lname.get()
email = entry_email.get()
age = entry_age.get()

vals = (user_id, fname, lname, email, age)
trv.insert('', END, values=vals)


btn_add['command'] = add


frame.grid(row=0, column=0)

label_id.grid(row=0, column=0, sticky='e')
entry_id.grid(row=0, column=1)

trv.grid(row=0, column=2, rowspan=5, padx=10, pady=10)

label_fname.grid(row=1, column=0, sticky='e')
entry_fname.grid(row=1, column=1)

label_lname.grid(row=2, column=0, sticky='e')
entry_lname.grid(row=2, column=1)

label_email.grid(row=3, column=0, sticky='e')
entry_email.grid(row=3, column=1)

label_age.grid(row=4, column=0, sticky='e')
entry_age.grid(row=4, column=1)

#frame_btns.grid(row=5, column=0, columnspan=2)
btn_add.grid(row=5, column=0, columnspan=2, sticky='nsew', pady=20, padx=(10,0))




root.mainloop()

OUTPUT:

Python Tkinter Treeview Insert Row
Python Tkinter Treeview Add Row - Before

Python Tkinter Treeview Add Row
Python Tkinter Treeview Add Row - After






Share this

Related Posts

Previous
Next Post »