Python 2.7 Linux
我只使用idlelib.TreeWidget在Tkinter.Canvas中创建一个树,没有别的。
如何获取所选树节点的信息(例如名称)?我需要稍后访问此信息。
我可以在选择/双击Canvas时调用一个函数,但不确定如何使用树节点:
self.canvas.bind('<Double-Button-1>', self.onSave)
请运行以下代码(请注意,每个Canvas中有2棵树,1棵树):
from Tkinter import Tk, Frame, BOTH, Canvas
from xml.dom.minidom import parseString
from idlelib.TreeWidget import TreeItem, TreeNode
class DomTreeItem(TreeItem):
def __init__(self, node):
self.node = node
def GetText(self):
node = self.node
if node.nodeType == node.ELEMENT_NODE:
return node.nodeName
elif node.nodeType == node.TEXT_NODE:
return node.nodeValue
def IsExpandable(self):
node = self.node
return node.hasChildNodes()
def GetSubList(self):
parent = self.node
children = parent.childNodes
prelist = [DomTreeItem(node) for node in children]
itemlist = [item for item in prelist if item.GetText().strip()]
return itemlist
data = '''
<angel>
<digital_core>
<radio_top>d</radio_top>
<uart_top>e</uart_top>
</digital_core>
<digital_core>
<c>f</c>
</digital_core>
</angel>
'''
class Application(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background = "white")
self.parent = parent
# Maximize window
self.screenWidth = self.parent.winfo_screenwidth() - 5
self.screenHeight = self.parent.winfo_screenheight() - 110
self.parent.geometry('%dx%d+%d+%d' % (self.screenWidth, self.screenHeight, 0, 0))
self.parent.resizable(0, 0)
dom = parseString(data)
item = DomTreeItem(dom.documentElement)
self.canvas = Canvas(self, bg = "cyan")
self.canvas.grid(column = 0, row = 0, rowspan = 2, sticky = 'NSWE', padx = 5, pady = 5)
node = TreeNode(self.canvas, None, item)
node.update()
self.canvas2 = Canvas(self, bg = "yellow")
self.canvas2.grid(column = 1, row = 0, rowspan = 2, sticky = 'NSWE', padx = 5, pady = 5)
node2 = TreeNode(self.canvas2, None, item)
node2.update()
parent.configure(bg = "black")
self.pack(fill = BOTH, expand = True, padx = 20, pady = 20)
def main():
root = Tk()
Application(root)
root.mainloop()
if __name__ == '__main__':
main()
答案 0 :(得分:2)
我看到的最直接的方法是访问TreeNode
的字段以检索传递到TreeNode
构造函数的内容。
例如,
node.parent
node.canvas
node.item
要从DomTreeItem
获取文字,您可以
node.item.GetText()
您还可以通过查看
中的方法获取更多信息dir(node.item)
答案 1 :(得分:2)
DanGar的回答很有帮助,但不完全是我想要的。
TreeItem已经有内置函数GetSelectedIconName和OnDoubleClick,所以我在修改后的类中使用它来获取选择的名称:
class DomTreeItem(TreeItem):
def __init__(self, node):
self.node = node
def GetText(self):
node = self.node
if node.nodeType == node.ELEMENT_NODE:
return node.nodeName
elif node.nodeType == node.TEXT_NODE:
return node.nodeValue
def IsExpandable(self):
node = self.node
return node.hasChildNodes()
def GetSubList(self):
parent = self.node
children = parent.childNodes
prelist = [DomTreeItem(node) for node in children]
itemlist = [item for item in prelist if item.GetText().strip()]
return itemlist
def GetSelectedIconName(self):
print self.node.nodeName
def OnDoubleClick(self):
print "double-clicked"