我已經創建了2個樹,在畫布上,左側和右側是idlelib.TreeWidget。Python Tkinter:樹的選擇
我也能夠打印出一個樹節點的名稱,如果雙擊,但我需要的是雙擊一個樹節點將使某個樹節點可見和選擇。
我在這裏有一個簡單的例子。如果雙擊左側的「level1」,則右側的「ccc」應該可見並自動選擇。你是怎樣做的?
請運行下面的代碼:
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
def OnDoubleClick(self):
print self.node.nodeName
left = '''
<level0>
<level1/>
</level0>
'''
right = '''
<aaa>
<bbb> <ccc/> </bbb>
</aaa>
'''
class Application(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.parent.geometry('%dx%d+%d+%d' % (800, 300, 0, 0))
self.parent.resizable(0, 0)
dom = parseString(left)
item = DomTreeItem(dom.documentElement)
self.canvas = Canvas(self, bg = "cyan")
self.canvas.grid(column = 0, row = 0, sticky = 'NSWE')
node = TreeNode(self.canvas, None, item)
node.update()
dom2 = parseString(right)
item2 = DomTreeItem(dom2.documentElement)
self.canvas2 = Canvas(self, bg = "yellow")
self.canvas2.grid(column = 1, row = 0, sticky = 'NSWE')
node2 = TreeNode(self.canvas2, None, item2)
node2.update()
self.pack(fill = BOTH, expand = True)
def main():
root = Tk()
Application(root)
root.mainloop()
if __name__ == '__main__':
main()
我喜歡你的解決方案,確實非常快速和骯髒。但是,如果有一個以上的孩子呢?如果我們知道節點的名稱,那麼擴展一下:node2.children [0] .expand() –
我剛剛發現了:node2.children [0] .__ dict__給了我們對象屬性,並且我發現它的TreeItem屬性。所以只需檢查node2.children [0] .item.GetText() –
你想回答我的其他問題:http://stackoverflow.com/questions/22996833/python-tkinter-canvas-scrolling-with-mousewheel –