Python 单击 Tkinter Treeview 小部件的项目的命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3794268/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Command for clicking on the items of a Tkinter Treeview widget?
提问by Rafe Kettler
I'm creating a GUI with Tkinter, and a major part of the GUI is two Treeview objects. I need the contents of the Treeviewobjects to changewhen an item (i.e. a directory) is clicked twice.
我正在用 Tkinter 创建一个 GUI,GUI 的主要部分是两个 Treeview 对象。当一个项目(即一个目录)被单击两次时,我需要改变Treeview对象的内容。
If Treeview items were buttons, I'd just be able to set commandto the appropriate function. But I'm having trouble finding a way to create "on_click"behavior for Treeview items.
如果 Treeview 项目是按钮,我就可以设置command为适当的功能。但是我无法找到一种"on_click"为 Treeview 项目创建行为的方法。
What Treeview option, method, etc, enables me to bind a command to particular items and execute that command "on_click"?
什么 Treeview 选项、方法等使我能够将命令绑定到特定项目并执行该命令"on_click"?
采纳答案by Bryan Oakley
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:
如果您希望在用户双击时发生某些事情,请将绑定添加到"<Double-1>". 由于单击即可设置选择,因此在您的回调中,您可以查询小部件以找出选择的内容。例如:
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()
回答by Csaba
The previous solution fails when multiple elements are selected and the user uses SHIFT+CLICK(at least on a Mac).
The previous solution fails when multiple elements are selected and the user uses SHIFT+CLICK(at least on a Mac).
Here is a better solution:
这是一个更好的解决方案:
import tkinter as tk
import tkinter.ttk as 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.identify('item',event.x,event.y)
print("you clicked on", self.tree.item(item,"text"))
if __name__ == "__main__":
app = App()
回答by Matthew Martinez
I know this is old but this code will also print multiple selected item in a treeview.
我知道这是旧的,但此代码还将在树视图中打印多个选定的项目。
def on_double_click(self, event):
item = self.tree.selection()
for i in item:
print("you clicked on", self.tree.item(i, "values")[0])

