Search code examples
pythonpython-3.xtkintertreeview

Display Treeview data on click and hide on click - Tkinter


I have this little Tkinter treeview program where data is being displayed in form of table and there is also a button there. So what I want to know is to be able to hide and display the data of table just by clicking the same display button. like if i click once it shows and when i click it again it hides its data.

With data I mean all IDs and Names it showing

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

ID = [1,2,3,4,5, 6, 7, 8, 9]
Names = ['Tom', 'Rob', 'Tim', 'Jim', 'Kim', 'Kim', 'Kim', 'Kim']

window = tk.Tk()
window.state('zoomed')
treev = ttk.Treeview(window, selectmode ='browse')
treev.place(width= 250, height= 500, x=300, y=100)


verscrlbar = ttk.Scrollbar(window,
                           orient ="vertical",
                           command = treev.yview)

verscrlbar.pack(side ='right', fill ='y')
treev.configure(yscrollcommand = verscrlbar.set)


treev["columns"] = ('1', '2')

treev['show'] = 'headings'

treev.column("1", width = 90, anchor ='c')
treev.column("2", width = 90, anchor ='c')


treev.heading("1", text ="ID")
treev.heading("2", text ="Names")

for x, y in zip(ID, Names):
    treev.insert("", 'end', values =(x, y))

displaybutton = Button(window, text="Display", width=15, height=2, background= 'brown')
displaybutton.place(x=600, y=400)

window.mainloop()

Solution

  • We create this by simply inserting the values in the treeview on click and for the next click we can delete everything we inserted in the treeview.

    a = 2
    def showhide():
        global a
        if a%2 == 0:
            for x, y in zip(ID, Names):
                treev.insert("", 'end', values =(x, y))
    
            a= a+1
        else:
            c = treev.get_children()
            for child in c:
                treev.delete(child)
            a= a+1