Tkinter Treeview Selection Option Occurrence and Event Trigger
There are three selection modes in the Treeview control, BROWSE (default), EXTENDED, and NONE, which are set using the selectmode parameter, and generate the virtual event `<
Example#1
Using the default BROWSE option, only one item can be selected at a time, and the selected item will be displayed synchronously in the status bar at the bottom of the window when the selection occurs.
from tkinter import *
from tkinter.ttk import *
def treeSelect(event):
widgetObj = event.widget # Get controls
itemselected = widgetObj.selection()[0] # Get options
col1 = widgetObj.item(itemselected,"text") # Get icon bar content
col2 = widgetObj.item(itemselected,"values")[0] # Get the content of the 0th index field
str = "{0} : {1}".format(col1,col2) #
var.set(str) # Set the status bar content
root = Tk()
root.title("apidemos.com")
stateCity = {"Illinois": "Chicago", "California": "Los Angeles",
"Texas": "Houston", "Washington": "Seattle",
"Jiangsu": "Nanjing", "Shandong": "Qingdao",
"Guangdong": "Guangzhou", "Fujian": "Xiamen"}
# Create Treeview
tree = Treeview(root,columns=("cities"),selectmode=BROWSE)
# Create column headings
tree.heading("#0",text="State")
tree.heading("cities",text="City")
# Format field
tree.column("cities",anchor=CENTER)
# Build content, line number from 1 to even lines are light blue background
tree.tag_configure("evenColor",background="lightblue")
rowCount = 1
for state in stateCity.keys():
if (rowCount % 2 == 1):
tree.insert("",index=END,text=state,values=stateCity[state])
else:
tree.insert("",index=END,text=state,
values=stateCity[state],tags=("evenColor"))
rowCount += 1
tree.bind("<<TreeviewSelect>>",treeSelect)
tree.pack()
var = StringVar()
label = Label(root,textvariable=var,relief="groove")
label.pack(fill=BOTH,expand=True)
root.mainloop()
Output:
Line 23 above sets the selectmode=BROWSE parameter specifically when creating the Treeview control object just to emphasize this mode, because this is the default mode, so if you omit this setting you will also get the same result. Line 37 of the program refers to the treeSelect( ) event handler when a selection item occurs.
Line 5 is to get the control in the window where this event occurs and set it to widgetObj. Line 6 is the Treeview control object widgetObj calling the selection( ) method to get the currently selected item, represented by itemselected, which is also commonly referred to as the iid, which is the internal id used by tkinter. This is the id used internally by tkinter.
Lines 7 and 8 call the item( ) method from the control object widgetObj. Note that two parameters are needed here to get the contents of the icon bar and the index bar of the selected item. Line 9 is to format the obtained content, and line 10 is to set the content to the status bar.