Tkinter Treeview Double-click an item
When using the Treeview control, it is often necessary to perform double-click operations, most often to open a document. This section will explain this aspect. When a double click occurs in a Treeview control, a <Double-1>
event is generated, which we can use to build an event handler for the double click.
For this type of problem, another focus is to obtain the double-click item, which will be explained with an example below.
Example#1
When double-clicking on an item in the Treeview control, a dialog box appears listing the selected item.
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
def doubleClick(event):
e = event.widget # Get event controls
iid = e.identify("item",event.x,event.y) # Get the double-click item id
state = e.item(iid,"text") # Get state
city = e.item(iid,"values")[0] # Get city
outputStr = "{0} : {1}".format(state,city) # Formatting
messagebox.showinfo("Double Clicked",outputStr) # Output
root = Tk()
root.title("ch18_12")
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"))
# Create column headings
tree.heading("#0",text="State") # Icon bar
tree.heading("cities",text="City")
# Format field
tree.column("cities",anchor=CENTER)
# Create Content
for state in stateCity.keys():
tree.insert("",index=END,text=state,values=stateCity[state])
tree.bind("<Double-1>",doubleClick) # Double-click binding doubleClick method
tree.pack()
root.mainloop()
Output:
Line 31 of the above program binds the double-click operation to the doubleClick( ) method, so when a double-click is made the doubleClick( ) method in lines 5 to 11 will be executed. Line 6 is to get the control of the double-click event, and line 7 identifi( ) method is used as follows.
iid = e.identify("item",event.x,event.y)
The first parameter xxx can be item, column, row, which are the coordinates of the double click, and get the information of item, column or row when double clicked, this example is using item, so we can get which item was double clicked. Line 8 is to get the "text" information of the double click, which is the state content. Line 9 is to get the "values" information of the double click, which is the City content. Line 9 is to get the formatted string and line 10 is to get the showinfo message dialog.