我在Canvas中创建了两个带有idlelib.TreeWidget的树,左右。
如果双击,我可以打印出树节点的名称,但是我需要的是双击树节点,仅从左侧打印出消息。
请运行以下代码(左侧树是self.canvas,右侧是self.canvas2):
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
content = '''
<level0>
<level1/>
</level0>
'''
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(content)
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(content)
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()
答案 0 :(得分:0)
您只需要修改DomTreeItem
类以获取一个参数,该参数确定它是否应该双击:
class DomTreeItem(TreeItem):
def __init__(self, node, doubleclick=True): # set the value of double-click
self.node = node
self.doubleclick = doubleclick # make the value an instance variable
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, self.doubleclick) for node in children] # pass it to the nodes
itemlist = [item for item in prelist if item.GetText().strip()]
return itemlist
def OnDoubleClick(self):
if self.doubleclick: # check if it's set to True
print self.node.nodeName # and only print it then
然后,当您创建该类的新实例时,只需将doubleclick
设置为True
或False
。如果您不希望在第二个树上触发双击,请将其实例化为:
item2 = DomTreeItem(dom2.documentElement, doubleclick=False)