本文整理汇总了Python中tkinter.ttk.Treeview.delete方法的典型用法代码示例。如果您正苦于以下问题:Python Treeview.delete方法的具体用法?Python Treeview.delete怎么用?Python Treeview.delete使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tkinter.ttk.Treeview
的用法示例。
在下文中一共展示了Treeview.delete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: DataTree
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
class DataTree(Frame):
def __init__(self, master):
Frame.__init__(self, master, bg="black")
scroll = Scrollbar(self)
self.tree = Treeview(self, yscrollcommand=scroll.set)
scroll.config(command=self.tree.yview)
self.items = []
self.tree.pack(side=LEFT, fill=BOTH, expand=1)
scroll.pack(side=LEFT, fill=Y)
def update(self, files):
self.files = files
# reversing, since removing a node with children removes the children as
# well. there might be a cleaner way to do this by clearing each of the
# file nodes, but that might add more burden to the garbage collector
# down the line.
for item in reversed(self.items):
self.tree.delete(item)
self.items = []
for (i, datafile) in enumerate(self.files):
self.add_file(datafile, i)
def add_file(self, f, f_id):
file_id = self.tree.insert("", "end", text=f.name)
self.items.append(file_id)
self.add_node(file_id, f.data, f_id)
def add_node(self, p, node, f_id):
if node.name != '':
node_id = self.tree.insert(p, "end", text=node.name,
values=(f_id, node.path))
self.items.append(node_id)
else:
node_id = p
if node.is_grp:
for child in node.children:
self.add_node(node_id, child, f_id)
示例2: Window
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
class Window(Tk):
def __init__(self):
super().__init__()
self.title('Treepace Tree Transformation GUI Demo')
self.geometry('640x400')
self.resizable(False, False)
self.tree_frame = Frame()
self.tree_button = Button(self.tree_frame, text="Load tree",
command=self.load)
self.tree_button.pack(expand=True, fill=BOTH)
self.tree_text = Text(self.tree_frame, width=20)
self.tree_text.pack(expand=True, fill=BOTH)
self.tree_text.insert('1.0', DEFAULT_TREE)
self.tree_frame.pack(side=LEFT, expand=True, fill=BOTH)
self.program_frame = Frame()
self.program_button = Button(self.program_frame, text="Transform",
command=self.transform)
self.program_button.pack(expand=True, fill=BOTH)
self.program_text = Text(self.program_frame, width=60, height=8)
self.program_text.pack(expand=True, fill=BOTH)
self.program_text.insert('1.0', DEFAULT_PROGRAM)
self.tv = Treeview(self.program_frame)
self.tv.pack(expand=True, fill=BOTH)
self.program_frame.pack(side=LEFT, expand=True, fill=BOTH)
GuiNode.tv = self.tv
self.load()
def load(self):
if self.tv.exists('root'):
self.tv.delete('root')
program = self.tree_text.get('1.0', END)
self.tree = Tree.load(program, IndentedText, GuiNode)
def transform(self):
try:
self.tree.transform(self.program_text.get('1.0', END))
except Exception as e:
messagebox.showerror("Transformation error", e)
示例3: DialogPluginManager
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
#.........这里部分代码省略.........
enableDisableFrame = Frame(frame)
enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3)
enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll)
ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240)
disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll)
ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240)
enableAllButton.grid(row=1, column=1)
disableAllButton.grid(row=1, column=2)
self.loadTreeViews()
self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
frame.grid(row=0, column=0, sticky=(N,S,E,W))
frame.columnconfigure(0, weight=0)
frame.columnconfigure(1, weight=1)
frame.rowconfigure(0, weight=1)
window = self.winfo_toplevel()
window.columnconfigure(0, weight=1)
window.rowconfigure(0, weight=1)
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.modulesView.get_children(""):
self.modulesView.delete(previousNode)
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))
示例4: DialogPackageManager
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
#.........这里部分代码省略.........
packageInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
packageInfoFrame.config(borderwidth=4, relief="groove")
okButton = Button(frame, text=_("Close"), command=self.ok)
ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
cancelButton = Button(frame, text=_("Cancel"), command=self.close)
ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
self.loadTreeViews()
self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
frame.grid(row=0, column=0, sticky=(N,S,E,W))
frame.columnconfigure(0, weight=0)
frame.columnconfigure(1, weight=1)
frame.rowconfigure(0, weight=1)
window = self.winfo_toplevel()
window.columnconfigure(0, weight=1)
window.rowconfigure(0, weight=1)
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()
示例5: CopyFileFrame
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
class CopyFileFrame(CopilotInnerFrame):
def __init__(self, master, config, state):
super(CopyFileFrame, self).__init__(master, config)
self._state = state
self._item_paths = {}
self._tree = Treeview(self._master, columns=('size'))
self._tree.heading('size', text='Size')
self._tree.grid(row=1, column=0, columnspan=3, sticky='nsew')
self._tree.configure(yscrollcommand=self._sb.set)
self._sb['command'] = self._tree.yview
if self._state.action == 'copy':
self._next_btn['text'] = 'Copy'
self._frame_lbl['text'] = 'Copy File'
self._populate_tree(self._config.file_root)
elif self._state.action == 'delete':
self._next_btn['text'] = 'Delete'
self._frame_lbl['text'] = 'Delete File'
self._populate_tree(self._state.to_device.part().mount())
self._next_btn['command'] = self._next_cmd
def _next_cmd(self):
if self._state.action == 'copy':
self._copy_file()
elif self._state.action == 'delete':
self._delete_file()
def _copy_file(self):
cur_item = self._tree.focus()
cur_path = self._item_paths.get(cur_item, '')
if cur_path != '':
new_path = os.path.join(self._state.device_to_path, os.path.basename(cur_path))
try:
if os.path.exists(new_path):
if ConfirmFrame.show(
self._master, self._config,
'The file already exists in the destination.\n'
'Would you like to overwrite it?',
'Yes', 'No'
):
shutil.copyfile(cur_path, new_path)
else:
shutil.copyfile(cur_path, new_path)
except PermissionError:
OkFrame.show(
self._master, self._config,
'Error copying file:\n\nInvalid permissions'
)
except Exception as e:
OkFrame.show(
self._master, self._config,
'An error occurred while copying the file:\n\n{}'.format(e)
)
def _delete_file(self):
cur_item = self._tree.focus()
cur_path = self._item_paths.get(cur_item, '')
if cur_path != '':
disp_path = cur_path[len(self._state.to_device.part().mount()):]
try:
if ConfirmFrame.show(
self._master, self._config,
'Are you sure you\'d like to delete this file?\n{}'.format(disp_path),
'Yes', 'No'
):
os.remove(cur_path)
self._tree.delete(self._tree.focus())
except PermissionError:
OkFrame.show(
self._master, self._config,
'Error deleting file:\n\nInvalid permissions'
)
except Exception as e:
OkFrame.show(
self._master, self._config,
'An error occurred while deleting the file:\n\n{}'.format(e)
)
def _populate_tree(self, tree_root):
self._item_paths = {}
def insert_path(tree, path, parent_id):
dirs = [e for e in scandir(path) if e.is_dir()]
dirs.sort(key=lambda e: e.name)
for d in dirs:
dir_name = d.name
dir_id = '{}-{}'.format(parent_id, dir_name)
dir_path = os.path.join(path, dir_name)
tree.insert(parent_id, 'end', dir_id, text=dir_name, tags=('dir'))
try:
insert_path(tree, dir_path, dir_id)
except:
pass
files = [e for e in scandir(path) if e.is_file()]
#.........这里部分代码省略.........
示例6: DialogPluginManager
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
#.........这里部分代码省略.........
ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240)
self.moduleRemoveButton.grid(row=7, column=3, sticky=E)
moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
moduleInfoFrame.config(borderwidth=4, relief="groove")
okButton = Button(frame, text=_("Close"), command=self.ok)
ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
cancelButton = Button(frame, text=_("Cancel"), command=self.close)
ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
self.loadTreeViews()
frame.grid(row=0, column=0, sticky=(N,S,E,W))
frame.columnconfigure(0, weight=1)
frame.columnconfigure(1, 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.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"),
示例7: ComponentsDumpWindow
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
#.........这里部分代码省略.........
# Таблица рассчитанных значений
columns = ("№ стержня", "x", "Nx", "U", "σ")
self.tree = Treeview(self, columns = columns, displaycolumns = columns)
self.tree.grid(column = 0, row = 1, columnspan = 7, sticky = W + N + E + S)
self.tree.column("#0", width = 0, stretch = 0)
# Настройки отображения таблицы
self.tree.column(columns[0], anchor = CENTER)
self.tree.heading(columns[0], text = columns[0], anchor = CENTER)
for x in columns[1:]:
self.tree.column(x, anchor = E)
self.tree.heading(x, text = x, anchor = E)
self.rowconfigure(1, weight = 1)
self.bind("<Destroy>", self.onWindowDestroy)
self.updateTitles()
self.onConstructionChanged(False)
def updateTitles(self):
if self.barNumber is None:
titleDescStr = ""
xDescStr = "global"
else:
titleDescStr = "%sСтержень (%d)" % (self.application.nameDelim, self.barNumber)
xDescStr = "local"
self.title("%s%sКомпоненты%s" \
% (self.application.name, self.application.nameDelim, titleDescStr))
self.fromLabel["text"] = "От x(" + xDescStr + "):"
self.toLabel["text"] = "До x(" + xDescStr + "):"
def onWindowDestroy(self, event):
self.application.onWindowDestroy(self)
def onCalculateButtonClicked(self):
try:
self.calculate()
except Exception as e:
self.showError(e)
def onConstructionChanged(self, constructed = True):
if not constructed:
for var in self.fromVar, self.toVar, self.stepVar:
var.set("0")
return
try:
self.calculate()
except Exception:
self.clear()
def onPointCalculated(self, barNumber, x, N, U, Sigma):
if self.barNumber is not None and barNumber != self.barNumber:
return
self.tree.insert(parent = "", index = "end",
values = ("—" if barNumber is None else str(barNumber),
"%.14f" % x, "%.14f" % N,
"%.14f" % U, "%.14f" % Sigma))
def clear(self):
self.tree.delete(*self.tree.get_children())
def calculate(self):
self.clear()
if self.barNumber not in range(0, self.application.logic.barsCount()):
self.barNumber = None
self.updateTitles()
for var in self.fromVar, self.toVar, self.stepVar:
try:
float(var.get())
except ValueError:
var.set("0")
xFrom = float(self.fromVar.get())
xTo = float(self.toVar.get())
xStep = float(self.stepVar.get())
self.application.logic.calculateComponents(xFrom, xTo, xStep, barNumber = self.barNumber,
onPointCalculated = self.onPointCalculated)
def showError(self, message):
tkinter.messagebox.showerror("Ошибка", message)
示例8: DialogOpenArchive
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
#.........这里部分代码省略.........
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):
self.title(title)
self.openType = openType
selectedNode = None
# clear previous treeview entries
for previousNode in self.treeView.get_children(""):
self.treeView.delete(previousNode)
# set up treeView widget and tabbed pane
if openType in (ARCHIVE, DISCLOSURE_SYSTEM):
self.treeView.column("#0", width=500, anchor="w")
self.treeView.heading("#0", text=colHeader)
try:
self.isRss = self.filesource.isRss
if self.isRss:
self.treeView.column("#0", width=350, anchor="w")
self.treeView["columns"] = ("descr", "date", "instDoc")
self.treeView.column("descr", width=50, anchor="center", stretch=False)
self.treeView.heading("descr", text="Form")
self.treeView.column("date", width=170, anchor="w", stretch=False)
self.treeView.heading("date", text="Pub Date")
self.treeView.column("instDoc", width=200, anchor="w", stretch=False)
self.treeView.heading("instDoc", text="Instance Document")
except AttributeError:
self.isRss = False
self.treeView["columns"] = tuple()
loadedPaths = []
for i, filename in enumerate(self.filenames):
if isinstance(filename,tuple):
if self.isRss:
form, date, instDoc = filename[2:5]
filename = filename[0] # ignore tooltip
self.hasToolTip = True
if filename.endswith("/"):
filename = filename[:-1]
path = filename.split("/")
if not self.isRss and len(path) > 1 and path[:-1] in loadedPaths:
parent = "file{0}".format(loadedPaths.index(path[:-1]))
示例9: BioInfo
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
#.........这里部分代码省略.........
Label(self.frameFoldC, text="foldCh").pack(side=LEFT)
self.entryFoldC = Entry(self.frameFoldC, width=6)
self.entryFoldC.pack(side=LEFT)
# Form note
self.frameNote = Frame(self.frameForms)
self.frameNote.pack()
Label(self.frameNote, text="note ").pack(side=LEFT)
self.entryNote = Entry(self.frameNote, width=6)
self.entryNote.pack(side=LEFT)
# Bouton comparer
self.buttonComparer = Button(self, text="Comparer", command=self.compare, width=10, state=DISABLED)
self.buttonComparer.pack(fill= X, expand="yes", padx=20, pady=(10,0))
#Bouton exporter
self.buttonExport = Button(self, text="Exporter", command=self.export, width=10, state=DISABLED)
self.buttonExport.pack(fill= X, expand="yes", padx=20)
# Réinitialiser
self.buttonReset = Button(self, text="Réinitialiser", command=self.reset, width=10)
self.buttonReset.pack(fill= X, expand="yes", padx=20, pady=(0,10))
# file members
self.list1 = None
self.list2 = None
def load_fileList1(self):
fname = askopenfilename(filetypes=(("CSV files", "*.csv"),
("All files", "*.*") ))
if fname:
self.entrylist1.delete(0, END)
self.list1 = fname
self.entrylist1.insert(0,fname)
self.buttonComparer.config(state=NORMAL)
def load_fileList2(self):
fname = askopenfilename(filetypes=(("CSV files", "*.csv"),
("All files", "*.*") ))
if fname:
self.entrylist2.delete(0, END)
self.list2 = fname
self.entrylist2.insert(0,fname)
self.buttonComparer.config(state=NORMAL)
else:
showerror("Erreur : fichier B", "La liste B est introuvable")
def resetTree (self):
for i in self.tree.get_children():
self.tree.delete(i)
def reset(self):
self.list1 = None
self.entrylist1.delete(0, END)
self.list2 = None
self.entrylist2.delete(0, END)
self.entryPVal.delete(0,END)
示例10: Gr
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
class Gr():
def __init__(self,root,data,SCRY=None):
self.data=data
self.columns=[x for x in range(1,8)]+['day']
root.rowconfigure(1,weight=1)
root.columnconfigure(0,weight=1)
root.columnconfigure(1,weight=1)
root.columnconfigure(2,weight=1)
f=Frame(root)
f.columnconfigure(0,weight=1)
f.rowconfigure(1,weight=1)
self.v=Combobox(root)
self.v.grid(row=0,column=0)
self.v.bind('<<ComboboxSelected>>',self.select_ver)
f.grid(row=1,column=0,columnspan=3,sticky=N+S)
self.tree=Treeview(f,
columns=self.columns,
displaycolumns=['day']+self.columns[:-1],
show='headings')
#self.tree.tag_configure('odd',background='white')
#self.tree.tag_configure('even',background='gray')
self.tree.tag_configure('dif',foreground='brown')
self.tree.tag_configure('work',background='white')
self.tree.tag_configure('short',background='#F5EFE0')
self.tree.tag_configure('rest',background='#E0B0B0')
self.tree.tag_configure('holyday',background='#E7B7A4')
for c in self.columns:
self.tree.heading(c,text=c)
self.tree.column(c,width=65,anchor='center')
self.tree.column('day',width=30)
scrX=Scrollbar(f,orient='horizontal',command=self.tree.xview)
self.tree['xscrollcommand']=scrX.set
if not SCRY:
self.scrY=Scrollbar(f,orient='vertical',command=self.yview)
self.tree['yscrollcommand']=self.scrY.set
else:
self.tree['yscrollcommand']=SCRY.set
self.tree.grid(row=1,column=0,sticky=N+S)
if not SCRY:
self.scrY.grid(row=1,column=1,sticky=N+S)
scrX.grid(row=2,column=0,sticky=E+W)
def set(self,y,m):
self.y=y
self.m=m
self.show()
def yview(self,*args):
self.tree.yview(*args)
self.yview2(*args)
def yview2(self,*args):
pass
def show(self):
d=self.data[self.y][self.m]
V=list(d['degur'].keys())
self.v['values']=V
self.v.set(V[0])
self.select_ver()
def select_ver(self,*e):
self.tree.delete(*self.tree.get_children())
d=self.data[self.y][self.m]
offset=d['offset']
v=self.v.get()
col=[]
for i,deg in enumerate(d['degurs']):
self.tree.heading(i+1,text=deg)
col.append(i+1)
self.tree.configure(displaycolumns=['day']+col)
items=dict()
if 'табель' in d['degur']:
a=[''.join(x) for x in zip(*[[x for x in d['degur']['план'][j]] \
for j in d['degurs']])]
b=[''.join(x) for x in zip(*[[x for x in d['degur']['табель'][j]] \
for j in d['degurs']])]
c=[x!=y for x,y in zip(a,b)]
else:
c=[False]*32
for i in range(1,d['days']+1):
tag = (i+offset) % 7 in [0,6] and 'rest' or 'work'
if i in d['holydays'] : tag='holyday'
elif i in d['restdays'] : tag='rest'
elif i in d['shortdays'] : tag='short'
elif i in d['workdays'] : tag='work'
if c[i]: tag=[tag,'dif']
ii=self.tree.insert('','end',values=['-','-','-','-','-'],tag=tag)
self.tree.set(ii,column='day',value=i)
items[i]=ii
for j,s in d['degur'][v].items(): # j-degur
if not s: continue
for i,val in enumerate(s[1:-1]):
if val=='J':
val='до'
elif val=='j':
val='од'
elif val=='a':
val='10'
self.tree.set(items[i+1],column=d['degurs'].index(j)+1,value=val)
if s[0]=='Н':
#.........这里部分代码省略.........
示例11: ElementListWidget
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
#.........这里部分代码省略.........
# Корректируем номера элементов
self.tree.set(item, "№", index - 1)
self.tree.set(prev, "№", index)
self.updateSelectedFrame(item)
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()
示例12: DialogOpenArchive
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [as 别名]
#.........这里部分代码省略.........
window.columnconfigure(0, weight=1)
window.rowconfigure(0, weight=1)
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):
self.title(title)
self.openType = openType
selectedNode = None
# clear previous treeview entries
for previousNode in self.treeView.get_children(""):
self.treeView.delete(previousNode)
# set up treeView widget and tabbed pane
if openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
if openType in (PLUGIN, PACKAGE): width = 770
else: width = 500
self.treeView.column("#0", width=width, anchor="w")
self.treeView.heading("#0", text=colHeader)
self.isRss = getattr(self.filesource, "isRss", False)
if self.isRss:
self.treeView.column("#0", width=350, anchor="w")
self.treeView["columns"] = ("descr", "date", "instDoc")
self.treeView.column("descr", width=50, anchor="center", stretch=False)
self.treeView.heading("descr", text="Form")
self.treeView.column("date", width=170, anchor="w", stretch=False)
self.treeView.heading("date", text="Pub Date")
self.treeView.column("instDoc", width=200, anchor="w", stretch=False)
self.treeView.heading("instDoc", text="Instance Document")
elif openType == PLUGIN:
self.treeView.column("#0", width=150, anchor="w")
self.treeView["columns"] = ("name", "vers", "descr", "license")
self.treeView.column("name", width=150, anchor="w", stretch=False)
self.treeView.heading("name", text="Name")
self.treeView.column("vers", width=60, anchor="w", stretch=False)
self.treeView.heading("vers", text="Version")
self.treeView.column("descr", width=300, anchor="w", stretch=False)
self.treeView.heading("descr", text="Description")
self.treeView.column("license", width=60, anchor="w", stretch=False)
self.treeView.heading("license", text="License")
elif openType == PACKAGE:
self.treeView.column("#0", width=200, anchor="w")
self.treeView["columns"] = ("vers", "descr", "license")
self.treeView.column("vers", width=100, anchor="w", stretch=False)
示例13: Tree
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [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)
示例14: NameView
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [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
示例15: fillTree
# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import delete [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))