单击时显示 Treeview 数据并在单击时隐藏 - Tkinter

Display Treeview data on click and hide on click - Tkinter

我有这个 Tkinter 树视图小程序,其中数据以 table 的形式显示,那里还有一个按钮。所以我想知道的是只需要点击同一个显示按钮就可以隐藏和显示table的数据。就像我点击一次它显示,当我再次点击它时它隐藏它的数据。

对于数据,我指的是它显示的所有 ID 和名称

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

其中一种方法是逐行分离。为此,您需要将所有项目 iid 存储在一个数组中。 treev.get_children() 将 return 所有项目 id。您稍后可以使用 detach()reattach()(或 move()

来删除和显示行
from tkinter import ttk
import tkinter as tk
from tkinter import *

def hide():
    
    global a
        
    if not treev.get_children():
       for  x, child in enumerate(a):
           treev.reattach(item=child, parent=treev.parent(a[0]), index=x) # or you could give parent as an empty string like parent=''

    else:
        for child in a:
            treev.detach(child)
 

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)

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

treev['show'] = 'headings'

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

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))

a = treev.get_children()

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

window.mainloop()

我们通过简单地在点击时在树视图中插入值来创建它,对于下一次点击,我们可以删除我们在树视图中插入的所有内容。

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