Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

python - Command for clicking on the items of a Tkinter Treeview widget?

I'm creating a GUI with Tkinter, and a major part of the GUI is two Treeview objects. I need the contents of the Treeview objects to change when an item (i.e. a directory) is clicked twice.

If Treeview items were buttons, I'd just be able to set command to the appropriate function. But I'm having trouble finding a way to create "on_click" behavior for Treeview items.

What Treeview option, method, etc, enables me to bind a command to particular items and execute that command "on_click"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want something to happen when the user double-clicks, add a binding to "<Double-1>". Since a single click sets the selection, in your callback you can query the widget to find out what is selected. For example:

import tkinter as tk
from tkinter import ttk

class App:
    def __init__(self):
        self.root = tk.Tk()
        self.tree = ttk.Treeview()
        self.tree.pack()
        for i in range(10):
            self.tree.insert("", "end", text="Item %s" % i)
        self.tree.bind("<Double-1>", self.OnDoubleClick)
        self.root.mainloop()

    def OnDoubleClick(self, event):
        item = self.tree.selection()[0]
        print("you clicked on", self.tree.item(item,"text"))

if __name__ == "__main__":
    app = App()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...