本文整理汇总了Python中tkinter.ttk.Treeview.selection方法的典型用法代码示例。如果您正苦于以下问题:Python Treeview.selection方法的具体用法?Python Treeview.selection怎么用?Python Treeview.selection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.ttk.Treeview
的用法示例。
在下文中一共展示了Treeview.selection方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DialogPluginManager
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
#.........这里部分代码省略.........
def loadSubtree(parentNode, moduleItems):
for moduleItem in sorted(moduleItems, key=lambda item: item[0]):
moduleInfo = moduleItem[1]
if parentNode or not moduleInfo.get("isImported"):
nodeName = moduleItem[0]
if parentNode:
nodeName = parentNode + GROUPSEP + nodeName
name = moduleInfo.get("name", nodeName)
node = self.modulesView.insert(parentNode, "end", nodeName, text=name)
self.modulesView.set(node, "author", moduleInfo.get("author"))
self.modulesView.set(node, "ver", moduleInfo.get("version"))
self.modulesView.set(node, "status", moduleInfo.get("status"))
self.modulesView.set(node, "date", moduleInfo.get("fileDate"))
if name in self.modulesWithNewerFileDates:
self.modulesView.set(node, "update", _("available"))
self.modulesView.set(node, "descr", moduleInfo.get("description"))
self.modulesView.set(node, "license", moduleInfo.get("license"))
if moduleInfo.get("imports"):
loadSubtree(node, [(importModuleInfo["name"],importModuleInfo)
for importModuleInfo in moduleInfo["imports"]])
loadSubtree("", self.pluginConfig.get("modules", {}).items())
# clear previous treeview entries
for previousNode in self.classesView.get_children(""):
self.classesView.delete(previousNode)
for i, classItem in enumerate(sorted(self.pluginConfig.get("classes", {}).items())):
className, moduleList = classItem
node = self.classesView.insert("", "end", className, text=className)
self.classesView.set(node, "modules", ', '.join(moduleList))
self.moduleSelect() # clear out prior selection
def ok(self, event=None):
if self.pluginConfigChanged:
PluginManager.pluginConfig = self.pluginConfig
PluginManager.pluginConfigChanged = True
PluginManager.reset() # force reloading of modules
if self.uiClassMethodsChanged or self.modelClassesChanged or self.disclosureSystemTypesChanged or self.hostSystemFeaturesChanged: # may require reloading UI
affectedItems = ""
if self.uiClassMethodsChanged:
affectedItems += _("menus of the user interface")
if self.modelClassesChanged:
if affectedItems:
affectedItems += _(" and ")
affectedItems += _("model objects of the processor")
if self.disclosureSystemTypesChanged:
if affectedItems:
affectedItems += _(" and ")
affectedItems += _("disclosure system types")
if self.hostSystemFeaturesChanged:
if affectedItems:
affectedItems += _(" and ")
affectedItems += _("host system features")
if messagebox.askyesno(_("User interface plug-in change"),
_("A change in plug-in class methods may have affected {0}. "
"Please restart Arelle to due to these changes. \n\n"
"Should Arelle restart itself now "
"(if there are any unsaved changes they would be lost!)?"
).format(affectedItems),
parent=self):
self.cntlr.uiThreadQueue.put((self.cntlr.quit, [None, True]))
self.close()
示例2: DialogPluginManager
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
#.........这里部分代码省略.........
self.protocol("WM_DELETE_WINDOW", self.close)
self.grab_set()
self.wait_window(self)
def loadTreeViews(self):
self.selectedModule = None
# clear previous treeview entries
for previousNode in self.modulesView.get_children(""):
self.modulesView.delete(previousNode)
for i, moduleItem in enumerate(sorted(self.pluginConfig.get("modules", {}).items())):
moduleInfo = moduleItem[1]
name = moduleInfo.get("name", moduleItem[0])
node = self.modulesView.insert("", "end", name, text=name)
self.modulesView.set(node, "author", moduleInfo.get("author"))
self.modulesView.set(node, "ver", moduleInfo.get("version"))
self.modulesView.set(node, "status", moduleInfo.get("status"))
self.modulesView.set(node, "date", moduleInfo.get("fileDate"))
if name in self.modulesWithNewerFileDates:
self.modulesView.set(node, "update", _("available"))
self.modulesView.set(node, "descr", moduleInfo.get("description"))
self.modulesView.set(node, "license", moduleInfo.get("license"))
# clear previous treeview entries
for previousNode in self.classesView.get_children(""):
self.classesView.delete(previousNode)
for i, classItem in enumerate(sorted(self.pluginConfig.get("classes", {}).items())):
className, moduleList = classItem
node = self.classesView.insert("", "end", className, text=className)
self.classesView.set(node, "modules", ', '.join(moduleList))
self.moduleSelect() # clear out prior selection
def ok(self, event=None):
if self.pluginConfigChanged:
PluginManager.pluginConfig = self.pluginConfig
PluginManager.pluginConfigChanged = True
PluginManager.reset() # force reloading of modules
if self.uiClassMethodsChanged: # may require reloading UI
if messagebox.askyesno(_("User interface plug-in change"),
_("A change in plug-in class methods may have affected the menus "
"of the user interface. It may be necessary to restart Arelle to "
"access the menu entries or the changes to their plug-in methods. \n\n"
"Should Arelle restart with changed user interface language, "
"(if there are any unsaved changes they would be lost!)?"),
parent=self):
self.cntlr.uiThreadQueue.put((self.cntlr.quit, [None, True]))
self.close()
def close(self, event=None):
self.parent.focus_set()
self.destroy()
def moduleSelect(self, *args):
node = (self.modulesView.selection() or (None,))[0]
moduleInfo = self.pluginConfig.get("modules", {}).get(node)
if moduleInfo:
self.selectedModule = node
name = moduleInfo["name"]
self.moduleNameLabel.config(text=name)
self.moduleAuthorHdr.config(state=ACTIVE)
self.moduleAuthorLabel.config(text=moduleInfo["author"])
self.moduleDescrHdr.config(state=ACTIVE)
self.moduleDescrLabel.config(text=moduleInfo["description"])
示例3: DialogPackageManager
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
#.........这里部分代码省略.........
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.close)
self.protocol("WM_DELETE_WINDOW", self.close)
self.grab_set()
self.wait_window(self)
def loadTreeViews(self):
self.selectedModule = None
# clear previous treeview entries
for previousNode in self.packagesView.get_children(""):
self.packagesView.delete(previousNode)
for i, packageInfo in enumerate(self.packagesConfig.get("packages", [])):
name = packageInfo.get("name", "package{}".format(i))
node = self.packagesView.insert("", "end", "_{}".format(i), text=name)
self.packagesView.set(node, "ver", packageInfo.get("version"))
self.packagesView.set(node, "status", packageInfo.get("status"))
self.packagesView.set(node, "date", packageInfo.get("fileDate"))
if name in self.packageNamesWithNewerFileDates:
self.packagesView.set(node, "update", _("available"))
self.packagesView.set(node, "descr", packageInfo.get("description"))
# clear previous treeview entries
for previousNode in self.remappingsView.get_children(""):
self.remappingsView.delete(previousNode)
for i, remappingItem in enumerate(sorted(self.packagesConfig.get("remappings", {}).items())):
prefix, remapping = remappingItem
node = self.remappingsView.insert("", "end", prefix, text=prefix)
self.remappingsView.set(node, "remapping", remapping)
self.packageSelect() # clear out prior selection
def ok(self, event=None):
if self.packagesConfigChanged:
PackageManager.packagesConfig = self.packagesConfig
PackageManager.packagesConfigChanged = True
self.cntlr.onPackageEnablementChanged()
self.close()
def close(self, event=None):
self.parent.focus_set()
self.destroy()
def packageSelect(self, *args):
node = (self.packagesView.selection() or (None,))[0]
try:
nodeIndex = int(node[1:])
except (ValueError, TypeError):
nodeIndex = -1
if 0 <= nodeIndex < len(self.packagesConfig["packages"]):
packageInfo = self.packagesConfig["packages"][nodeIndex]
self.selectedPackageIndex = nodeIndex
name = packageInfo["name"]
self.packageNameLabel.config(text=name)
self.packageVersionHdr.config(state=ACTIVE)
self.packageVersionLabel.config(text=packageInfo["version"])
self.packageDescrHdr.config(state=ACTIVE)
self.packageDescrLabel.config(text=packageInfo["description"])
self.packagePrefixesHdr.config(state=ACTIVE)
self.packagePrefixesLabel.config(text=', '.join(packageInfo["remappings"].keys()))
self.packageUrlHdr.config(state=ACTIVE)
self.packageUrlLabel.config(text=packageInfo["URL"])
self.packageDateHdr.config(state=ACTIVE)
示例4: Expenses
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
#.........这里部分代码省略.........
if(itemType == "All"):
self.obtainData("Tree")
self.obtainData("Animal")
self.obtainData("Machine")
else:
self.obtainData(itemType)
# Adds database data to the inventory table
def obtainData(self, type):
for row in (self.inventoryDB.getOverviewInventory(type)):
name = row[0]
totalQuantity = row[1]
# Inserts data into the table. Each entry is tagged with the name and the type
# This is done in order to make identifying the entries easier for when detailed
# tables are requested
self.tree.insert("", "end", values = (name,totalQuantity), tag= [name, type])
# Creates a bak function that is used in the displayGeneralInventory functions
self.backFunction = self.displayGeneralInventory
# Binds a double click function to the Treeview table. If an entry is double clicked,
# the function displayGeneralInventory is ran
self.tree.bind("<Double-1>", self.displayDetailedInventory)
backButton = Button(root, text="Back", command=lambda: self.sequence(self.viewInveroty)) # This button will return the user to the main page. Still working on it.
backButton.place(x = 50, y = 350)
# Creates table when an entry is double clicked
def displayDetailedInventory(self, event):
# The selected item's tag are extracted and assigned to name and type
itemSelected = self.tree.selection()
name = self.tree.item(itemSelected,"tag")[0]
type = self.tree.item(itemSelected, "tag")[1]
for child in root.winfo_children():
child.destroy()
self.createDisplayTable()
self.obtainDetailedData(name, type)
# Adds detailed database data to the inventory table
def obtainDetailedData(self,name, type):
for row in (self.inventoryDB.getDetailedInventory(type, name)):
name = row[0]
purchaseDate = row[1]
Quantity = row[3]
Price = row[4]
self.tree.insert("", "end", values = (name,purchaseDate,Quantity, Price))
backButton = Button(root, text="Back", command=lambda: self.sequence(self.backFunction))
backButton.place(x = 50, y = 350)
# Creates the view total cost by month and year buttons
def viewTotalCost(self):
viewMonth = Button(root, text="View by month", command=lambda: self.sequence(self.viewByMonth))
viewMonth.place(x = 120, y = 100)
viewYear = Button(root, text="View by year", command=lambda: self.sequence(self.viewByYear))
viewYear.place(x = 120, y = 150)
backButton = Button(root, text="Back", command=lambda: self.sequence(self.createOptionButtons))#displayGeneralInventory)) # This button will return the user to the main page. Still working on it.
backButton.place(x = 50, y = 350)
示例5: DialogOpenArchive
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
class DialogOpenArchive(Toplevel):
def __init__(self, mainWin, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
parent = mainWin.parent
super(DialogOpenArchive, self).__init__(parent)
self.parent = parent
self.showAltViewButton = showAltViewButton
parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
dialogX = int(parentGeometry.group(3))
dialogY = int(parentGeometry.group(4))
self.accepted = False
self.transient(self.parent)
frame = Frame(self)
treeFrame = Frame(frame, width=500)
vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
hScrollbar["command"] = self.treeView.xview
hScrollbar.grid(row=1, column=0, sticky=(E,W))
vScrollbar["command"] = self.treeView.yview
vScrollbar.grid(row=0, column=1, sticky=(N,S))
treeFrame.columnconfigure(0, weight=1)
treeFrame.rowconfigure(0, weight=1)
treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
self.treeView.focus_set()
mainWin.showStatus(_("loading archive {0}").format(filesource.url))
self.filesource = filesource
self.filenames = filenames
self.selection = filesource.selection
self.hasToolTip = False
selectedNode = None
if openType == ENTRY_POINTS:
try:
metadataFiles = filesource.taxonomyPackageMetadataFiles
if len(metadataFiles) > 1:
raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
.format(', '.join(metadataFiles)))
metadataFile = metadataFiles[0]
metadata = filesource.file(filesource.url + os.sep + metadataFile)[0]
self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
if self.metadataFilePrefix:
self.metadataFilePrefix += os.sep
self.nameToUrls, self.remappings = parseTxmyPkg(mainWin, metadata)
except Exception as e:
self.close()
err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
messagebox.showerror(_("Malformed taxonomy package"), err)
mainWin.addToLog(err)
return
mainWin.showStatus(None)
if openType == DISCLOSURE_SYSTEM:
y = 3
else:
y = 1
okButton = Button(frame, text=_("OK"), command=self.ok)
cancelButton = Button(frame, text=_("Cancel"), command=self.close)
okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
if showAltViewButton:
self.altViewButton = Button(frame, command=self.showAltView)
self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
self.loadTreeView(openType, colHeader, title)
frame.grid(row=0, column=0, sticky=(N,S,E,W))
frame.columnconfigure(0, weight=1)
window = self.winfo_toplevel()
window.columnconfigure(0, weight=1)
self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
self.bind("<Return>", self.ok)
self.bind("<Escape>", self.close)
self.toolTipText = StringVar()
if self.hasToolTip:
self.treeView.bind("<Motion>", self.motion, '+')
self.treeView.bind("<Leave>", self.leave, '+')
self.toolTipText = StringVar()
self.toolTip = ToolTip(self.treeView,
textvariable=self.toolTipText,
wraplength=640,
follow_mouse=True,
state="disabled")
self.toolTipRowId = None
self.protocol("WM_DELETE_WINDOW", self.close)
self.grab_set()
self.wait_window(self)
def loadTreeView(self, openType, title, colHeader):
#.........这里部分代码省略.........
示例6: ElementListWidget
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
#.........这里部分代码省略.........
def onButtonDownClicked(self):
item = self.selectedItem()
if item is None: return
next = self.tree.next(item)
if next != "":
parent, index = self.tree.parent(item), self.tree.index(item)
self.tree.move(item, parent, index + 1)
# Корректируем номера элементов
self.tree.set(item, "№", index + 1)
self.tree.set(next, "№", index)
self.updateSelectedFrame(item)
def onButtonAddClicked(self):
pass
def onButtonRemoveClicked(self):
item = self.selectedItem()
if item is None: return
next = self.tree.next(item)
self.tree.delete(item)
while next != "":
i = int(self.tree.set(next, "№"))
self.tree.set(next, "№", i - 1)
next = self.tree.next(next)
self.onSelectionChanged()
def onButtonApplyClicked(self, item = None):
if item is None: item = self.selectedItem()
if item is None: return None
label = self.label[0].get()
self.tree.set(item, "Метка", label)
return item
def onSelectionChanged(self, event = None):
item = self.selectedItem()
# Обновляем состояние кнопок
state = DISABLED if item is None else NORMAL
for x in (self.buttonRemove, self.buttonUp, self.buttonDown):
x["state"] = state
self.updateSelectedFrame(item)
def selectedItem(self):
selection = self.tree.selection()
return None if type(selection) == type("") else selection[0]
def clear(self):
for item in self.tree.get_children():
self.tree.delete(item)
def updateSelectedFrame(self, item = None, values = None):
if item is None: item = self.selectedItem()
values = None
if item is None:
i = ""
label = ""
else:
if values is None: values = self.tree.set(item)
i = values["№"]
label = values["Метка"]
self.i.set(i)
self.label[0].set(label)
return (item, values)
def addElement(self, values):
self.tree.insert(parent = "", index = END, values = values)
def setDefaultElement(self, label):
self.label[1].set(label)
def elementsCount(self):
return len(self.tree.get_children())
def elements(self, transform):
return [ transform(item) for item in self.tree.get_children() ]
示例7: DialogOpenArchive
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
class DialogOpenArchive(Toplevel):
def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
if isinstance(parent, Cntlr):
cntlr = parent
parent = parent.parent # parent is cntlrWinMain
else: # parent is a Toplevel dialog
cntlr = parent.cntlr
super(DialogOpenArchive, self).__init__(parent)
self.parent = parent
self.showAltViewButton = showAltViewButton
parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
dialogX = int(parentGeometry.group(3))
dialogY = int(parentGeometry.group(4))
self.accepted = False
self.transient(self.parent)
frame = Frame(self)
treeFrame = Frame(frame, width=500)
vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
hScrollbar["command"] = self.treeView.xview
hScrollbar.grid(row=1, column=0, sticky=(E,W))
vScrollbar["command"] = self.treeView.yview
vScrollbar.grid(row=0, column=1, sticky=(N,S))
treeFrame.columnconfigure(0, weight=1)
treeFrame.rowconfigure(0, weight=1)
treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
self.treeView.focus_set()
if openType not in (PLUGIN, PACKAGE):
cntlr.showStatus(_("loading archive {0}").format(filesource.url))
self.filesource = filesource
self.filenames = filenames
self.selection = filesource.selection
self.hasToolTip = False
selectedNode = None
if openType == ENTRY_POINTS:
try:
metadataFiles = filesource.taxonomyPackageMetadataFiles
''' take first for now
if len(metadataFiles) != 1:
raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
.format(', '.join(metadataFiles)))
'''
metadataFile = metadataFiles[0]
metadata = filesource.url + os.sep + metadataFile
self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
if self.metadataFilePrefix:
self.metadataFilePrefix += "/" # zip contents have /, never \ file seps
self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
os.path.splitext(os.path.basename(filesource.url))[0])
self.taxonomyPackage = parsePackage(cntlr, filesource, metadata,
os.sep.join(os.path.split(metadata)[:-1]) + os.sep)
if self.taxonomyPackage["entryPoints"]:
# may have instance documents too
self.packageContainedInstances = []
packageContentTypeCounts = {}
for suffix in (".xhtml", ".htm", ".html"):
for potentialInstance in filesource.dir:
if potentialInstance.endswith(".xhtml"):
_type = "Inline Instance"
self.packageContainedInstances.append([potentialInstance, _type])
packageContentTypeCounts[potentialInstance] = packageContentTypeCounts.get(potentialInstance, 0) + 1
if self.packageContainedInstances:
break
if self.packageContainedInstances: # add sequences to any duplicated entry types
for _type, count in packageContentTypeCounts.items():
if count > 1:
_dupNo = 0
for i in range(len(self.packageContainedInstances)):
if self.packageContainedInstances[i][0] == _type:
_dupNo += 1
self.packageContainedInstances[i][0] = "{} {}".format(_type, _dupNo)
else:
# may be a catalog file with no entry oint names
openType = ARCHIVE # no entry points to show, just archive
self.showAltViewButton = False
except Exception as e:
self.close()
err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
messagebox.showerror(_("Malformed taxonomy package"), err)
cntlr.addToLog(err)
return
if openType not in (PLUGIN, PACKAGE):
cntlr.showStatus(None)
if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
y = 3
else:
#.........这里部分代码省略.........
示例8: Tree
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
class Tree(LibraryListener):
def __init__(self, config, master):
self.views = config['views']
self.library = None
self.__make_widgets(master)
def __make_widgets(self, root):
self.tree = Treeview(root)
def on_library_change(self, library):
self.library = library
self.__make_root_nodes()
def __make_root_nodes(self):
for i in self.tree.get_children():
self.tree.delete(i)
root_nodes = self.query_library({}, self.views[0])
for node in root_nodes:
child = self.tree.insert("", "end", self.__make_node_id(None, self.views[0], node), text=node,
tags=self.views[0])
self.fetch_children(child)
@staticmethod
def __make_node_id(parent_node, node_type, node_value):
node_id = {}
if parent_node:
node_id = copy(parent_node)
node_id[node_type] = node_value
return node_id
def can_be_expanded(self, node_type):
return node_type != self.views[len(self.views) - 1]
def get_child_node_type(self, node_type):
return self.views[self.views.index(node_type) + 1]
def query_library(self, node_id, view):
return self.library.aggregate(node_id, view)
def __has_children(self, node):
return len(self.children(node)) > 0
def fetch_children(self, node):
if not self.__has_children(node):
node_type = self.tree.item(node, "tags")[0]
if self.can_be_expanded(node_type):
children_node_type = self.get_child_node_type(node_type)
node_id = literal_eval(node)
nodes = self.query_library(node_id, children_node_type)
for child_node in nodes:
self.tree.insert(node, "end", self.__make_node_id(node_id, children_node_type, child_node),
text=child_node, tags=children_node_type)
def delete_children(self, parent_node):
children = self.children(parent_node)
for node in children:
self.tree.delete(node)
@property
def selected_node(self):
if len(self.tree.selection()):
return self.tree.selection()[0]
def children(self, node):
return self.tree.get_children(node)
示例9: NameView
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
class NameView(object):
"""Shows a treeview of unique names."""
def __init__(self, master, names):
self.widget = Frame(master)
self._tree = Treeview(self.widget, columns='name')
self._tree.grid(row=0,column=0, sticky=(N,S,W,E))
self._tree.view = self
self.widget.columnconfigure(0, weight=1)
self.widget.rowconfigure(0,weight=1)
self._tree.column('name', width=50)
self._tree['show'] = 'tree'
actions = {'edit': lambda e: self.edit(),
'search': lambda e: self.search(),
'focus_next': lambda e: self.focus_next(),
'focus_prev': lambda e: self.focus_prev(),
'select': lambda e: self._tree.selection_toggle(self._tree.focus()),
'clear_selection': lambda e: self._tree.selection_set([])
}
kb.make_bindings(kb.tagview, actions, self._tree.bind)
self._iids = dict()
self._names = dict()
logger.debug('Names: %s', names)
self.widget.focus_set = self._tree.focus_set
for name in sorted(names):
iid = self._tree.insert('', 'end', text=name)
self._names[iid] = name
self._iids[name] = iid
self._scroll = Scrollbar(self.widget, command=self._tree.yview)
self._tree['yscrollcommand'] = self._scroll.set
self._scroll.grid(row=0, column=1, sticky=(N, S))
self.widget.columnconfigure(1, weight=0)
def selection(self):
logger.debug('Selection: %s', self._tree.selection())
return [self._names[iid] for iid in self._tree.selection()]
def edit(self):
self._tree.event_generate('<<NameViewEdit>>')
def search(self):
if len(self._tree.selection()) == 0:
self._tree.selection_add(self._tree.focus())
self._tree.event_generate('<<NameViewSearch>>')
def append(self, names):
logger.debug('Append names: %s', names)
for name in names:
if name not in self._names.values():
iid = self._tree.insert('', 'end', text=name)
self._names[iid] = name
self._iids[name] = iid
def delete(self, name):
self._tree.delete(self._iids[name])
del self._names[self._iids[name]]
del self._iids[name]
def _focus(self, iid):
self._tree.focus(iid)
self._tree.see(iid)
def focus_next(self):
cur_iid = self._tree.focus()
next_iid = self._tree.next(cur_iid)
if next_iid == '':
iids = self._tree.get_children()
next_iid = iids[0]
self._focus(next_iid)
def focus_prev(self):
cur_iid = self._tree.focus()
prev_iid = self._tree.prev(cur_iid)
if prev_iid == '':
iids = self._tree.get_children()
prev_iid = iids[-1]
self._focus(prev_iid)
def jump_to(self, name):
try:
iid = self._iids[name]
self._focus(iid)
except KeyError:
pass
def get_names(self):
return tuple(self._names.values())
def set(self, names):
self._tree.delete(*self._iids.values())
self._iids.clear()
self._names.clear()
for name in sorted(names):
iid = self._tree.insert('', 'end', text=name)
self._names[iid] = name
self._iids[name] = iid
示例10: fillTree
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import selection [as 别名]
class Window:
def fillTree(self,path, parent, list):
for file in os.listdir(path):
abspath = os.path.join(path,file)
color = ""
treelist = None
for mini in list:
if abspath in mini:
color = 'red'
treelist = mini
else:
for lk in mini:
if abspath in lk:
color = 'purple'
child = None
if color == 'red':
child = self.tree.insert(parent,'end',text=file,open=False,tags=(abspath,'red',str(treelist)),)
elif color == 'purple':
child = self.tree.insert(parent,'end',text=file,open=False,tags=(abspath,'purple'))
else:
child = self.tree.insert(parent,'end',text=file,open=False,tags=(abspath,'white'))
if(os.path.isdir(abspath)):
self.tree.insert(child,'end',text='',open=False)
def __init__(self,list,dirlist):
self.root = Tk()
self.root.wm_title("Duplicate_Files")
self.min = None
self.list = list
self.root.geometry('600x600+0+0')
self.tree = Treeview(self.root ,height=15)
self.tree.pack(expand='yes',fill='both')
self.tree.heading('#0',text="files")
self.tree.tag_configure('red',foreground='red')
self.tree.tag_configure('purple',foreground='#cc00ff')
self.tree.bind("<Double-1>",self.onDoubleClick)
self.tree.bind("<<TreeviewOpen>>",self.onOpen)
self.tree.bind("<<TreeviewClose>>",self.onClose)
for path in dirlist:
branch = self.tree.insert('','end',text=path,open=True,tags=(path,'white'))
self.fillTree(path,branch,list)
self.root.mainloop()
def onDoubleClick(self,event):
item = self.tree.selection()[0]
print ("clicked" + str(self.tree.item(item,'tags')[0]))
if str(self.tree.item(item,'tags')[1]) == "red":
list_of_files = ast.literal_eval(str(self.tree.item(item,'tags')[2]))
if self.min != None:
if self.min.mini.winfo_exists():
self.min.mini.destroy()
self.min = MiniWindow(self.root,list_of_files)
def onOpen(self,event):
item = self.tree.selection()[0]
if self.tree.parent(item) != '':
if len(self.tree.get_children(item))>0:
self.tree.delete(self.tree.get_children(item))
abspath = str(self.tree.item(item,'tags')[0])
if(os.path.isdir(abspath)):
self.fillTree(abspath, item,self.list)
def onClose(self,event):
item = self.tree.selection()[0]
if self.tree.parent(item) != '':
if len(self.tree.get_children(item))>0:
self.tree.delete(self.tree.get_children(item))