Tkinter Format content of Treeview fields
The column() method of the Treeview control is mainly used to format the content of a specific column, and its syntax format is as follows.
column(id, options)
Where the id is an indication of a specific column, either as a string or as an "#index" index. The following are the possible parameters of options.
(1) anchor
: you can set the column content reference position.
(2) minwidth
: the minimum column width, the default is 20 pixels.
(3) stretch
: default is 1, when the control size changes the column width will change with it.
(4) width
: the default column width is 200 pixels.
If you use this method without parameters, it is shown below.
ret = column(id)
will pass back the contents of all parameters of a particular column as a dictionary.
Example#1
Change the width of columns 1 and 2 to 150, while centering them, and leave the icon column unchanged.
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("apidemos.com")
# Create Treeview
tree = Treeview(root,columns=("cities","populations"))
# Create column headings
tree.heading("#0",text="State") # Icon bar
tree.heading("#1",text="City")
tree.heading("#2",text="Populations")
# Formatting fields
tree.column("#1",anchor=CENTER,width=150)
tree.column("#2",anchor=CENTER,width=150)
# Create Content
tree.insert("",index=END,text="Eleanor",values=("Chicago","800"))
tree.insert("",index=END,text="California",values=("LosAngeles","1000"))
tree.insert("",index=END,text="Tokyo",values=("Houston","900"))
tree.pack()
root.mainloop()
Output:
Example#2
To list all the contents of the cities field as a dictionary, this program adds only the following two lines.
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("apidemos.com")
# Create Treeview
tree = Treeview(root,columns=("cities","populations"))
# Create column headings
tree.heading("#0",text="State") # Icon bar
tree.heading("#1",text="City")
tree.heading("#2",text="Populations")
# Formatting fields
tree.column("#1",anchor=CENTER,width=150)
tree.column("#2",anchor=CENTER,width=150)
# Create Content
tree.insert("",index=END,text="Eleanor",values=("Chicago","800"))
tree.insert("",index=END,text="California",values=("LosAngeles","1000"))
tree.insert("",index=END,text="Tokyo",values=("Houston","900"))
tree.pack()
cityDict = tree.column("cities") # List all the contents of the cities field as a dictionary
print(cityDict)
root.mainloop()
Output:
The following is the result of the Python Shell window execution.