How to make table out of lists using TreeView Tkinter Python

六月ゝ 毕业季﹏ 提交于 2021-01-28 19:35:16

问题


What I want.. is to how create a table using TreeView Tkinter and data which is to be inserted in the table should from lists.

For example:

This is the list i have

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

And I want to create a table with headings "ID" and "Names" and I don't want to put each values in the table separately. Well this is a small list but even when I want to create a bigger table. So can anyone tell me how can I insert these list data in table automatically(loop).


回答1:


Just use for loop something like this:

from tkinter import ttk 
import tkinter as tk 

ID = [1,2,3,4,5, 6, 7, 8, 9]
Names = ['Tom', 'Rob', 'Tim', 'Jim', 'Kim', 'Kim', 'Kim', 'Kim']
  
window = tk.Tk() 

treev = ttk.Treeview(window, selectmode ='browse') 
treev.pack(side='left',expand=True, fill='both') 
  

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

window.mainloop() 

If You want a better way of doing it then use a dictionary:


from tkinter import ttk 
import tkinter as tk 

titles={'Id': [1,2,3,4,5, 6, 7, 8, 9], 'Names':['Tom', 'Rob', 'Tim', 'Jim', 'Kim', 'Kim', 'Kim', 'Kim', 'Kim'], 'Column': [1,2,3,4,5, 6, 7, 8, 9]}

  
window = tk.Tk() 

treev = ttk.Treeview(window, selectmode ='browse') 
treev.pack(side='left',expand=True, fill='both') 
  

verscrlbar = ttk.Scrollbar(window,  
                           orient ="vertical",  
                           command = treev.yview) 
  
verscrlbar.pack(side ='right', fill ='y')   
treev.configure(yscrollcommand = verscrlbar.set) 

treev["columns"] = list(x for x in range(len(list(titles.keys()))))
treev['show'] = 'headings'

  
for x, y in enumerate(titles.keys()):
    treev.column(x, minwidth=20, stretch=True,  anchor='c')
    treev.heading(x, text=y)

for args in zip(*list(titles.values())):
    treev.insert("", 'end', values =args) 

window.mainloop() 


来源:https://stackoverflow.com/questions/65530026/how-to-make-table-out-of-lists-using-treeview-tkinter-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!