当前位置: 首页>>代码示例>>Python>>正文


Python Treeview.insert方法代码示例

本文整理汇总了Python中tkinter.ttk.Treeview.insert方法的典型用法代码示例。如果您正苦于以下问题:Python Treeview.insert方法的具体用法?Python Treeview.insert怎么用?Python Treeview.insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tkinter.ttk.Treeview的用法示例。


在下文中一共展示了Treeview.insert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: per

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [as 别名]
class per():
    def __init__(self,data,y,v='план'):
        
        w=Toplevel()
        w.wm_title('Доп')
        w.columnconfigure(0,weight=1)
        w.rowconfigure(0,weight=1)
        
        years=sorted(data.keys())
        cols=data['2013']['degurs']  # ЗАГЛУШКА : список дежурных

        self.t=Treeview(w,columns=cols)
        for c in cols:
            self.t.heading(c,text=c)
            self.t.column(c,width=65,anchor='center')
        self.t.tag_configure('табель',background='green')
        self.t.tag_configure('ош',background='red')
        #self.t.tag_configure('табель',background='green')
        self.scrX=Scrollbar(w,orient='horizontal',command=self.t.xview)
        self.scrY=Scrollbar(w,orient='vertical',command=self.t.yview)
        self.t['xscrollcommand']=self.scrX.set
        self.t['yscrollcommand']=self.scrY.set
        self.t.grid(row=0,column=0,sticky=N+S+E+W)
        self.scrX.grid(row=1,column=0,sticky=E+W)
        self.scrY.grid(row=0,column=1,sticky=N+S)

        for y in years:
            x=self.t.insert('','end',text=y)
            eeY=[]
            for m in ['01','02','03','04','05','06','07','08','09','10','11','12']:
                d0=data[y]
                if m not in d0: continue
                d=d0[m]
                rez=dict()
                tag=''
                if v=='авто':
                    if 'табель' in d['degur']:
                        vv='табель'
                        tag=vv
                    else:
                        vv='план'
                elif v=='табель':
                    if 'табель' not in d['degur']:
                        vv='план'
                        tag='ош'
                    else:
                        vv=v
                        tag=vv
                else:
                    vv=v
                for j,s in d['degur'][vv].items():
                    rez[j]=analyse2(s,d)
                NUL=(0,0,0,0,0,0,0)
                ee=[rez.get(j,NUL)[0]-rez.get(j,NUL)[3]+rez.get(j,NUL)[4] for j in cols]
                eeY.append(ee)
                self.t.insert(x,'end',text=m,values=[x or '-' for x in ee],tag=tag)
            eeY=[sum(x) for x in zip(*eeY)]
            self.t.insert(x,'end',text='итого',values=eeY,tag='Y')
开发者ID:da-sher,项目名称:degur,代码行数:60,代码来源:degur.py

示例2: DataTree

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [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)
开发者ID:youngmit,项目名称:spectacuplot,代码行数:47,代码来源:DataTree.py

示例3: _maketree

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [as 别名]
def _maketree(parent_tree, wallpapers, conf):
    tree = Treeview(parent_tree)
    i = 0
    if conf['type'] == 'workspace':
        for workspace, wallpaper_files in wallpapers.items():
            i += 1
            index = str(i)
            tree.insert('', 'end', index, text=workspace)
            for j, wallpaper_file in enumerate(wallpaper_files):
                inner_index = index + '_' + str(j)
                tree.insert(index, 'end', inner_index, text=wallpaper_file)
    elif conf['type'] == 'desktop':
        for wallpaper_file in wallpapers:
            i += 1
            index = str(i)
            tree.insert('', 'end', index, text=wallpaper_file)
    tree.pack()
开发者ID:fernandoenzo,项目名称:wallpapoz,代码行数:19,代码来源:wallpapoz_main_window.py

示例4: Expenses

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [as 别名]
class Expenses(Frame):

    # Creates the first option menus in the expense window
    def createOptionButtons(self):
        self.master.title("Expenses")

        # Creates the add item to inventory button
        addItem = Button(root, text="Add item to inventory", command=lambda: self.sequence(self.addItem))#addItem(master)))  # This button will send to the user to the add item page
        addItem.place(x = 130, y = 100)

        # Creates the view items in inventory button
        inventoryButton = Button(root, text="View items in inventory", command=lambda: self.sequence(self.viewInveroty))  # This button will send the user to the view inventory page
        inventoryButton.place(x = 130, y = 150)

        # Create the total cost button
        totalCost = Button(root, text="Total Cost", command=lambda: self.sequence(self.viewTotalCost))
        totalCost.place(x = 130, y = 200)

        # Creates the back button
        backButton = Button(root, text="Back", command=returnHome)  # This button will return the user to the main page. Still working on it.
        backButton.place(x = 50, y = 350)

    # Creates the add item to inventory button and entries
    def addItem(self):
        self.master.title("Add new item")  # Changes the title of the page to Add New Item

        # Creates a label called nameOfItems and an entry called itemName
        nameOfItem = Label(root, text="Item Name: ")
        nameOfItem.place(x = 110, y = 100)
        self.itemName = Entry(root)       # This will allow the user to enter the name of the item that they will be adding
        self.itemName.place(x = 190, y = 100)

        # Creates the label called itemTypeLabel and a drop down menu called itemTypeChoice
        itemTypeLabel = Label(root, text = "Item's type: ")
        itemTypeLabel.place(x = 110, y = 160)
        self.itemTypeChoice = StringVar(root)       # This makes itemTypeChoice a permanent String
        self.itemTypeChoice.set("Tree")             # Tree is set to the default string of itemTypeChoice
        typeChoices = OptionMenu(root, self.itemTypeChoice, "Tree", "Animal", "Machine")    # Drop down menu is created and options Tree, Animal, and Machine are added to the menu
        typeChoices.place(x = 190, y = 160)


        backButton = Button(root, text = "Back", command=lambda: self.sequence(self.createOptionButtons))
        backButton.place(x = 50, y = 350)
        # Next button
        nextButton = Button(root, text = "Next", command=self.saveNameAndType) #This button will send the user to the add inventory page
        nextButton.place(x = 350, y = 350)

    # Function that creates a new item object and assigns it a name and the type
    def saveNameAndType(self):
        name = self.itemName.get()
        self.item = Inventory(name)
        itemType = self.itemTypeChoice.get()
        self.item.itemType = itemType
        self.sequence(self.addToInventory)

    # Creates the add to inventory options
    def addToInventory(self):
        self.master.title("Add %s to %s inventory" % (self.item.name, self.item.itemType))

        # This assigns the variables month, day, and year to be value holder for integer values
        # They are also set to be values of the class expenses (by using self) so that they can
        # be used in the function updateDay and SaveDate
        self.month = IntVar(self)
        self.day = IntVar(self)
        self.year = IntVar(self)

        # This trace function is used to keep track of when the selected months and years change. This is
        # done to adjust the days of the month according to the month or the year
        self.month.trace('w', self.updateDay)
        self.year.trace('w', self.updateDay)

        numMonths = self.nums(1, 12)  # Runs the nums function that creates a list from 1 to 12
        numYears = self.nums(2015, 2030)  # Runs the nums function that creates a list from 2015 to 2030

        # This creates the drop down menu and assigns the options is the menu. The day menu is left empty and
        # is assigned in the updateDay function
        self.optionmenu_month = OptionMenu(root, self.month, *numMonths)
        self.optionmenu_day = OptionMenu(root, self.day, '')
        self.optionmenu_year = OptionMenu(root, self.year, *numYears)

        # Sets the default value of the month and year options to 1 and 2015 respectively
        self.month.set(numMonths[0])
        self.year.set(numYears[0])

        self.optionmenu_month.place(x = 100, y = 120)
        self.optionmenu_day.place(x = 150, y = 120)
        self.optionmenu_year.place(x = 200, y = 120)


        datePurchased = Label(root, text = "Date Purchased")
        datePurchased.place(x = 150, y = 95)

        quantityPurchasedLabel = Label(root, text="Amount purchased:")
        quantityPurchasedLabel.place(x = 50, y = 180)
        self.quantityPurchasedEntry = Entry(root, bd=5) # Creates input box for user to insert the amount of items purchased
        self.quantityPurchasedEntry.place(x = 180, y = 180)

        pricePaidLabe = Label(root, text="Price paid for all: ")
        pricePaidLabe.place(x = 50, y = 210)
        self.pricePaidEntry = Entry(root, bd=5) # Creates input box for user to insert the price paid for the item
#.........这里部分代码省略.........
开发者ID:willgoishi,项目名称:CSCI_150_AG_Project,代码行数:103,代码来源:GUI_CLASS.py

示例5: Gui

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [as 别名]
class Gui(Interface):
    """The GUI interface uses the tkinter module to generate
    a window using tk
    """

    TREE_COLUMNS = ("Number of probes : {nProbes}", "Probe address", "Status")
    RESULT_DIPLAY_HEIGHT = 10

    def __init__(self, ip):
        Interface.__init__(self, ip)
        self.commandHistory = []
        self.mainWin = Tk()
        self.command = StringVar(self.mainWin)
        self.status = StringVar(self.mainWin, value="Waiting for command ...")
        self.text = StringVar(self.mainWin, value="Enter a command :")
        self.result = None
        self.probesDisplay = None
        self.mainWin.title("Commander for probe with ip : " + ip)
        self.isRunning = True
        self.mainWin.protocol("WM_DELETE_WINDOW", self.quit)

        # define the threads
        self.thProbe = Thread(target=self.updateProbes, name="Probe updater", daemon=True)
        self.thResults = Thread(target=self.updateResults, name="Results Updater", daemon=True)

    def start(self):
        """Starts (opens) the commander window"""
        self.mainWin.geometry("800x600")
        txtText = Label(self.mainWin, textvariable=self.text)
        txtText.grid(row=0, column=0, sticky=W)

        txtInput = Entry(self.mainWin, textvariable=self.command, width=30)
        txtInput.grid(row=0, column=1, sticky=E + W)
        txtInput.bind("<Return>", self.doCommand)
        txtInput.bind("<Up>", self.recallCommand)

        button = Button(self.mainWin, text="Refresh", fg="blue", command=self.triggerFetchProbes)
        button.grid(row=1, column=0, sticky=N + S + E + W)

        txtStatus = Label(self.mainWin, textvariable=self.status, wraplength=600, justify=CENTER)
        txtStatus.grid(row=1, column=1, sticky=N + S + E + W)

        self.probesDisplay = Treeview(self.mainWin, columns=self.TREE_COLUMNS, show="headings")
        self.probesDisplay.grid(row=2, columnspan=2, sticky=N + S + E + W)
        for i in range(0, len(self.TREE_COLUMNS)):
            self.updateHeading(i, nProbes=0)

        self.result = Text(self.mainWin, textvariable=self.result, height=self.RESULT_DIPLAY_HEIGHT, wrap=WORD)
        self.result.configure(state=DISABLED)
        self.result.grid(row=3, columnspan=2, sticky=N + S + E + W)
        self.addResult("Awaiting results .... ")

        self.mainWin.grid_rowconfigure(2, weight=1)
        self.mainWin.grid_columnconfigure(1, weight=1)

        self.probeFetcherScheduler()
        self.thProbe.start()

        self.resultFetcherScheduler()
        self.thResults.start()

        self.logger.info("Commander : Starting main window")

        self.mainWin.mainloop()

        self.logger.debug("Commander : mainloop over")

    def recallCommand(self, event):
        """Function to rewrite previous command in box"""
        if len(self.commandHistory) != 0:
            self.command.set(self.commandHistory[-1])
        return "break"

    def doCommand(self, event):
        """Executes user command"""
        self.commandHistory.append(self.command.get())
        self.logger.info("Commander : executing command")
        cmd = super().doCommand(self.command.get())
        # cmd.join()
        self.command.set("")

    def updateStatus(self, status):
        """Update status of the probe in status label
        :param status: new status"""
        self.status.set(status)
        self.mainWin.update_idletasks()

    def addResult(self, result):
        """Add (prepend) a result in the result test area
        :param result: the result to add
        """
        self.result.configure(state=NORMAL)
        self.result.insert("1.0", result + "\n")
        self.result.configure(state=DISABLED)

    def setResult(self, result):
        """Put this result in the result area
        :param result: result to put
        """
        self.result.configure(state=NORMAL)
#.........这里部分代码省略.........
开发者ID:nonsns,项目名称:NetProbes,代码行数:103,代码来源:gui.py

示例6: IncomeGUI

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [as 别名]
class IncomeGUI(Frame):   
    inDB = incomeDB()

    def createIncome(self):
        addIncome = Button(self, text="Add income", command=lambda: self.sequence(self.addMonth))
        addIncome.pack(fill=X, padx=10, pady=20)

        incomeButton = Button(self, text="View income", command =lambda: self.sequence(self.viewIncome))
        incomeButton.pack(fill=X, padx=10, pady=5)

        backButton = Button(self, text="Back")
        backButton.pack(side=BOTTOM)

    def addMonth(self):
        monthlabel = Label(self, text = "Select Month: ")
        monthlabel.pack()
        self.monthChoice = IntVar(self)
        months = self.numberings(1, 12)
        self.monthChoice.set(1) 
        self.monthInput = OptionMenu(self, self.monthChoice, *months)
        self.monthInput.pack()
        yearlabel = Label(self, text = "Select Year: ")
        yearlabel.pack()
        self.yearChoice = IntVar(self)
        years = self.numberings(2000, 2020)
        self.yearChoice.set(2000) 
        self.yearInput = OptionMenu(self, self.yearChoice, *years)
        self.yearInput.pack()
        

        nextButton = Button(self, text="Next", command=lambda: self.sequence(self.addIncome))
        nextButton.pack()
        backButton = Button(self, text="Back", command=lambda: self.sequence(
            self.createIncome))
        backButton.pack()

    def addIncome(self):
        month = self.monthChoice.get()
        self.income = income(month)
        self.income.year = self.yearChoice.get()

        amountlabel = Label(self, text="Amount of items sold this month: ")
        amountlabel.pack()
        self.amountinput = Entry(self)
        self.amountinput.pack()

        incomelabel = Label(self, text="Income earned: ")
        incomelabel.pack()
        self.incomeinput = Entry(self)
        self.incomeinput.pack()

        nextButton = Button(self, text="Next",
                            command= self.saveDetails)
        nextButton.pack()
        backButton = Button(self, text="Back", command=lambda: self.sequence(
            self.createIncome))
        backButton.pack()

    def saveDetails(self):
        self.income.amount = self.amountinput.get()
        self.income.income = self.incomeinput.get()
        self.sequence(self.confirmation)

    def confirmation(self):

        year = Label(self, text="Year: ")
        year.pack()
        yearin = Label(self, text=self.income.year)
        yearin.pack()

        month = Label(self, text="Month: ")
        month.pack()
        monthin = Label(self, text=self.income.month)
        monthin.pack()

        quantity = Label(self, text="Amount of items sold this month: ")
        quantity.pack()
        itemQuantity = Label(self, text=self.income.amount)
        itemQuantity.pack()

        price = Label(self, text="Income earned: ")
        price.pack()
        itemPrice = Label(self, text=self.income.income)
        itemPrice.pack()        

        nextButton = Button(self, text="Next",
                            command=lambda: self.sequence(self.addToIncomeDatabase))
        nextButton.pack()
        backButton = Button(self, text="Back", command=lambda: self.sequence(
            self.createIncome))
        backButton.pack()

    def addToIncomeDatabase(self):
        self.incomeDB.insertIntoDB(self.income)

        addedMessage = Message(self, text = "Added to database!")
        addedMessage.pack()

        endSessionButton = Button(self, text = "End Session", command=lambda: self.sequence(self.createIncome))
        endSessionButton.pack()
#.........这里部分代码省略.........
开发者ID:willgoishi,项目名称:CSCI_150_AG_Project,代码行数:103,代码来源:IncomeGUI.py

示例7: fillTree

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [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))
开发者ID:bretttjohnson1,项目名称:Duplicate_Discoverer,代码行数:68,代码来源:window.py

示例8: DialogPackageManager

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [as 别名]

#.........这里部分代码省略.........
        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()
                
    def packageSelect(self, *args):
        node = (self.packagesView.selection() or (None,))[0]
        try:
开发者ID:JagdishIdhate,项目名称:Arelle,代码行数:70,代码来源:DialogPackageManager.py

示例9: ComponentsDumpWindow

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [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)
开发者ID:DmitryKuk,项目名称:CompMech,代码行数:104,代码来源:ComponentsDumpWindow.py

示例10: statistic_xx

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [as 别名]
class statistic_xx():
    def __init__(self,data,y,v='план'):
        
        w=Toplevel()
        w.wm_title('Итоги по месяцам за {0} год ({1}) '.format(y,v))
        w.columnconfigure(0,weight=1)
        w.rowconfigure(0,weight=1)
        
        cols=data[y]['degurs']  # ЗАГЛУШКА : список дежурных
        
        self.t=Treeview(w,columns=cols)
        self.t.column('#0',width=120)
        for c in cols:
            self.t.heading(c,text=c)
            self.t.column(c,width=65,anchor='center')
        self.t.tag_configure('табель',background='green')
        self.t.tag_configure('ош',background='red')
        self.scrX=Scrollbar(w,orient='horizontal',command=self.t.xview)
        self.scrY=Scrollbar(w,orient='vertical',command=self.t.yview)
        self.t['xscrollcommand']=self.scrX.set
        self.t['yscrollcommand']=self.scrY.set
        self.t.grid(row=0,column=0,sticky=N+S+E+W)
        self.scrX.grid(row=1,column=0,sticky=E+W)
        self.scrY.grid(row=0,column=1,sticky=N+S)
        roots=dict()
        for m in ['01','02','03','04','05','06','07','08','09','10','11','12']:
            d0=data[y]
            if m not in d0: continue
            roots[m]=self.t.insert('','end',text=m+' ('+data[y][m]['month']+')')
        #r=self.t.insert('','end',text='рабочих')
        #x=self.t.insert('','end',text='xxx')
        #w=self.t.insert('','end',text='отработано')
        #e=self.t.insert('','end',text='дополнительные')
        #n=self.t.insert('','end',text='ночные')
        #h=self.t.insert('','end',text='праздничные')
        #rz_root=self.t.insert('','end',text='резерв')
        
        for m in ['01','02','03','04','05','06','07','08','09','10','11','12']:
            d0=data[y]
            if m not in d0: continue
            d=d0[m]

            rez=dict()
            tag=''
            if v=='авто':
                if 'табель' in d['degur']:
                    vv='табель'
                    tag=vv
                else:
                    vv='план'
            elif v=='табель':
                if 'табель' not in d['degur']:
                    vv='план'
                    tag='ош'
                else:
                    vv=v
                    tag=vv
            else:
                vv=v

            for j,s in d['degur'][vv].items():
                rez[j]=analyse2(s,d)
            NUL=(0,0,0,0,0,0,0)
            ww=[rez.get(j,NUL)[0] for j in cols]
            ee=[rez.get(j,NUL)[0]-rez.get(j,NUL)[3]+rez.get(j,NUL)[4] for j in cols]
            xx=[rez.get(j,NUL)[0]-rez.get(j,NUL)[3] for j in cols]
            nn=[rez.get(j,NUL)[1] for j in cols]
            hh=[rez.get(j,NUL)[2] for j in cols]
            rr=[rez.get(j,NUL)[3]-rez.get(j,NUL)[4] for j in cols]
            rz=[rez.get(j,NUL)[5] for j in cols]
            self.t.insert(roots[m],'end',text='отработано',values=ww,tag=tag)
            self.t.insert(roots[m],'end',text='рабочие',values=rr,tag=tag)
            self.t.insert(roots[m],'end',text='дополнительные',values=ee,tag=tag)
            self.t.insert(roots[m],'end',text='ночные',values=nn,tag=tag)
            self.t.insert(roots[m],'end',text='праздничные',values=hh,tag=tag)
开发者ID:da-sher,项目名称:degur,代码行数:77,代码来源:degur.py

示例11: Gr

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [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]=='Н':
#.........这里部分代码省略.........
开发者ID:da-sher,项目名称:degur,代码行数:103,代码来源:degur.py

示例12: ElementListWidget

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [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() ]
开发者ID:DmitryKuk,项目名称:CompMech,代码行数:104,代码来源:ElementListWidget.py

示例13: DialogOpenArchive

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [as 别名]

#.........这里部分代码省略.........
                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)
                self.treeView.heading("vers", text="Version")
                self.treeView.column("descr", width=400, anchor="w", stretch=False)
                self.treeView.heading("descr", text="Description")
                self.treeView.column("license", width=70, anchor="w", stretch=False)
                self.treeView.heading("license", text="License")
            else:
                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]
                    elif openType == PLUGIN:
                        name, vers, descr, license = filename[3:7]
                    elif openType == PACKAGE:
                        vers, descr, license = filename[3:6]
                    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]))
                else:
                    parent = "" 
                node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1])
                if self.isRss:
                    self.treeView.set(node, "descr", form)
                    self.treeView.set(node, "date", date)
                    self.treeView.set(node, "instDoc", os.path.basename(instDoc))
                elif openType == PLUGIN:
                    self.treeView.set(node, "name", name)
                    self.treeView.set(node, "vers", vers)
                    self.treeView.set(node, "descr", descr)
                    self.treeView.set(node, "license", license)
                elif openType == PACKAGE:
                    self.treeView.set(node, "vers", vers)
                    self.treeView.set(node, "descr", descr)
                    self.treeView.set(node, "license", license)
                if self.selection == filename:
                    selectedNode = node
                loadedPaths.append(path)

        elif openType == ENTRY_POINTS:
            self.treeView.column("#0", width=200, anchor="w")
            self.treeView.heading("#0", text="Name")
    
            self.treeView["columns"] = ("url",)
            self.treeView.column("url", width=300, anchor="w")
            self.treeView.heading("url", text="URL")
            
            for fileType, fileUrl in getattr(self, "packageContainedInstances", ()):
                self.treeView.insert("", "end", fileUrl, 
                                     values=fileType, 
                                     text=fileUrl or urls[0][2])
            for name, urls in sorted(self.taxonomyPackage["entryPoints"].items(), key=lambda i:i[0][2]):
                self.treeView.insert("", "end", name, 
                                     values="\n".join(url[1] for url in urls), 
开发者ID:Arelle,项目名称:Arelle,代码行数:70,代码来源:DialogOpenArchive.py

示例14: Tree

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [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)
开发者ID:realmassy,项目名称:MusicLibrary,代码行数:67,代码来源:ui.py

示例15: NameView

# 需要导入模块: from tkinter.ttk import Treeview [as 别名]
# 或者: from tkinter.ttk.Treeview import insert [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
开发者ID:gokai,项目名称:tim,代码行数:99,代码来源:tagview.py


注:本文中的tkinter.ttk.Treeview.insert方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。