[英]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. 我正在使用Tkinter创建GUI,GUI的主要部分是两个Treeview对象。 I need the contents of the Treeview
objects to change when an item (ie a directory) is clicked twice . 当单击一个项目(即目录) 两次时,我需要更改 Treeview
对象的内容。
If Treeview items were buttons, I'd just be able to set command
to the appropriate function. 如果Treeview项是按钮,我只能将command
设置为适当的功能。 But I'm having trouble finding a way to create "on_click"
behavior for Treeview items. 但我找不到为Treeview项创建"on_click"
行为的方法。
What Treeview option, method, etc, enables me to bind a command to particular items and execute that command "on_click"
? 什么Treeview选项,方法等,使我能够将命令绑定到特定项目并执行该命令"on_click"
?
If you want something to happen when the user double-clicks, add a binding to "<Double-1>"
. 如果您想在用户双击时发生某些事情,请将绑定添加到"<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()
The previous solution fails when multiple elements are selected and the user uses SHIFT+CLICK
(at least on a Mac). 选择多个元素并且用户使用SHIFT+CLICK
(至少在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()
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.