コード例 #1
0
    def __init__(self, root):
        super().__init__(root)
        self.root = root
        self.title(m.fullname[m.mode] + " options")
        self.grab_set()
        self.focus_set()
        self.resizable(FALSE, FALSE)
        placeWindow(self, 720, 350)
        self["padx"] = 10
        self["pady"] = 10
        
        self.parametersF = ParameterFrame(self, "Default parameters")

        # selection of directories
        self.fileDirectory = ChooseDirectoryFrame(self, "Default directory for file selection",
                                                  "FileDirectory", r'{}'.format(os.getcwd()),
                                                  False)

        # default time
        self.timeLabFrame = ttk.Labelframe(self, text = "Default time")
        self.timeFrame = TimeFrame(self.timeLabFrame, observe = False, loadtime = False)
        self.timeFrame.grid(row = 0, column = 0)
    
        # buttons
        self._createButtons()

        # grid of self contents        
        self.parametersF.grid(row = 0, column = 0, columnspan = 2, sticky = (N, W), padx = 4,
                              pady = 2)
        self.buttonFrame.grid(row = 3, column = 0, columnspan = 2, padx = 3, pady = 6,
                              sticky = (E, W, N, S))
        self.timeLabFrame.grid(row = 1, column = 1, padx = 6, pady = 4, sticky = (N, W, E))
        self.fileDirectory.grid(row = 1, column = 0, pady = 2, padx = 2, sticky = (E, W))
コード例 #2
0
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (10, 10, 12, 12)
        self.root = root
        self.fileStorage = self.root.fileStorage
        self.selectedBatchTime = optionGet("LastBatchTime", [(0, 20)], "list") # zkontrolovat ""

        # variables    
        self.status = StringVar()
        self.useBatchTimeVar = BooleanVar()
              
        # frames
        self.parametersF = ParameterFrame(self)
        self.fileStorageFrame= FileStorageFrame(self)
        self.saveToFrame = SaveToFrame(self, parent = "processor")
        self.optionFrame = OptionFrame(self, text = "Options")
        self.timeLabFrame = ttk.Labelframe(self, text = "Time")
        self.timeLabFrame.root = self
        self.timeFrame = TimeFrame(self.timeLabFrame)
        
        # buttons
        self.process = ttk.Button(self, text = "Process Files", command = self.processFun,
                                  state = "disabled")
        self.useBatchTime = ttk.Checkbutton(self.timeLabFrame, text = "Use batch time",
                                            variable = self.useBatchTimeVar,
                                            command = self.toggledUseBatchTime)
        self.setBatchTimeBut = ttk.Button(self.timeLabFrame, text = "Set", width = 3,
                                          command = self.setBatchTime)

        # labels
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.modeLab = ttk.Label(self, text = m.fullname[m.mode], font = ("Helvetica", "16"))
       
        # adding to grid
        self.parametersF.grid(column = 0, row = 3, columnspan = 4, sticky = (N, W), padx = 4)
        self.fileStorageFrame.grid(column = 3, row = 0, pady = 5, padx = 4)
        self.timeLabFrame.grid(column = 1, row = 5, padx = 30, sticky = (N, W))
        self.timeFrame.grid(column = 0, row = 0, columnspan = 2, sticky = (E, W))
        
        self.process.grid(column = 3, row = 7, sticky = (S, E), padx = 4, pady = 3)
        self.useBatchTime.grid(column = 0, row = 1, pady = 5)
        self.setBatchTimeBut.grid(column = 1, row = 1, pady = 5)

        self.statusBar.grid(column = 0, row = 7, columnspan = 3, sticky = (N, S, E, W), padx = 6,
                            pady = 3)
        self.modeLab.grid(column = 0, row = 0)
       
        self.saveToFrame.grid(column = 1, row = 1, columnspan = 3, sticky = (N, S, E, W),
                              padx = 6, pady = 2)

        self.optionFrame.grid(column = 0, row = 5, sticky = (N, E), padx = 6)
  
        # what should be enlarged
        self.columnconfigure(2, weight = 1)
        self.rowconfigure(2, weight = 3)
        self.rowconfigure(4, weight = 2)
        self.rowconfigure(6, weight = 2)
コード例 #3
0
ファイル: processor.py プロジェクト: bahniks/CM_Manager_0_3_4
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (10, 10, 12, 12)
        self.root = root  # potreba pouze pro progressbar

        # variables
        self.status = StringVar()

        # frames
        self.parametersF = ParameterFrame(self)
        self.fileStorageFrame = FileStorageFrame(self)
        self.saveToFrame = SaveToFrame(self, parent="processor")
        self.timeFrame = TimeFrame(self)
        self.optionFrame = OptionFrame(self, text="Options")

        # buttons
        self.process = ttk.Button(self,
                                  text="Process Files",
                                  command=self.processFun,
                                  state="disabled")

        # labels
        self.statusBar = ttk.Label(self, textvariable=self.status)

        # adding to grid
        self.parametersF.grid(column=0,
                              row=3,
                              columnspan=4,
                              sticky=(N, W),
                              padx=4)
        self.fileStorageFrame.grid(column=3, row=0, pady=5, padx=4)
        self.timeFrame.grid(column=1, row=5, padx=30, pady=15, sticky=(N, W))

        self.process.grid(column=3, row=7, sticky=(S, E), padx=4, pady=3)

        self.statusBar.grid(column=0,
                            row=7,
                            columnspan=3,
                            sticky=(N, S, E, W),
                            padx=6,
                            pady=3)

        self.saveToFrame.grid(column=1,
                              row=1,
                              columnspan=3,
                              sticky=(N, S, E, W),
                              padx=6,
                              pady=2)

        self.optionFrame.grid(column=0, row=5, sticky=(N, E), padx=6)

        # what should be enlarged
        self.columnconfigure(2, weight=1)
        self.rowconfigure(2, weight=3)
        self.rowconfigure(4, weight=2)
        self.rowconfigure(6, weight=2)
コード例 #4
0
ファイル: processor.py プロジェクト: bahniks/CM_Manager_0_3_4
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (10, 10, 12, 12)
        self.root = root # potreba pouze pro progressbar


        # variables    
        self.status = StringVar()
              
        # frames
        self.parametersF = ParameterFrame(self)
        self.fileStorageFrame= FileStorageFrame(self)
        self.saveToFrame = SaveToFrame(self, parent = "processor")
        self.timeFrame = TimeFrame(self)
        self.optionFrame = OptionFrame(self, text = "Options")
        
        # buttons
        self.process = ttk.Button(self, text = "Process Files", command = self.processFun,
                                  state = "disabled")

        # labels
        self.statusBar = ttk.Label(self, textvariable = self.status)

        
        # adding to grid
        self.parametersF.grid(column = 0, row = 3, columnspan = 4, sticky = (N, W), padx = 4)
        self.fileStorageFrame.grid(column = 3, row = 0, pady = 5, padx = 4)
        self.timeFrame.grid(column = 1, row = 5, padx = 30, pady = 15, sticky = (N, W))
        
        self.process.grid(column = 3, row = 7, sticky = (S, E), padx = 4, pady = 3)

        self.statusBar.grid(column = 0, row = 7, columnspan = 3, sticky = (N, S, E, W), padx = 6,
                            pady = 3)
       
        self.saveToFrame.grid(column = 1, row = 1, columnspan = 3, sticky = (N, S, E, W),
                              padx = 6, pady = 2)

        self.optionFrame.grid(column = 0, row = 5, sticky = (N, E), padx = 6)
  

        # what should be enlarged
        self.columnconfigure(2, weight = 1)
        self.rowconfigure(2, weight = 3)
        self.rowconfigure(4, weight = 2)
        self.rowconfigure(6, weight = 2)
コード例 #5
0
def main():
    import os.path
    import os
    from filestorage import FileStorage, recognizeFiles
    testGUI = Tk()
    testGUI.fileStorage = FileStorage()
    testGUI.timeFrame = TimeFrame(testGUI)
    testingDir = os.path.join(os.getcwd(), "TestingFiles")
    files = recognizeFiles(
        [os.path.join(testingDir, file) for file in os.listdir(testingDir)])
    testGUI.fileStorage.addFiles(files)
    testGUI.fileStorage.tag(files[1][1])
    testGUI.showtracks = ShowTracks(testGUI, files[1], files[1][1])
    testGUI.showtracks.grid()
    testGUI.showtracks.controlled = True
    testGUI.wm_withdraw()
    testGUI.mainloop()
コード例 #6
0
ファイル: options.py プロジェクト: bahniks/CM_Manager_0_3_4
class OptionsCM(Toplevel):
    "options window reachable from menu"

    def __init__(self, root):
        super().__init__(root)
        self.title("Options")
        self.grab_set()
        self.focus_set()
        self.resizable(FALSE, FALSE)
        placeWindow(self, 824, 844)
        self["padx"] = 10
        self["pady"] = 10

        self.parametersF = ParameterFrame(self, "Default parameters")

        # default filetype of processor output
        self.fileTypeVar = StringVar()
        self.fileTypeVar.set(
            optionGet("DefProcessOutputFileType", ".txt", "str"))

        self.fileTypeFrame = ttk.Labelframe(self,
                                            text="Default output filetype")

        self.txtRadioBut = ttk.Radiobutton(self.fileTypeFrame,
                                           text=".txt",
                                           variable=self.fileTypeVar,
                                           value=".txt")
        self.csvRadioBut = ttk.Radiobutton(self.fileTypeFrame,
                                           text=".csv",
                                           variable=self.fileTypeVar,
                                           value=".csv")

        self.txtRadioBut.grid(row=1, column=0, padx=2, pady=2, sticky=W)
        self.csvRadioBut.grid(row=0, column=0, padx=2, pady=2, sticky=W)

        # output separator
        self.separatorVar = StringVar()
        self.separatorVar.set(optionGet("ResultSeparator", ",", "str"))

        self.separatorFrame = ttk.Labelframe(self, text="Result separator")

        self.commaRadioBut = ttk.Radiobutton(self.separatorFrame,
                                             text="Comma",
                                             variable=self.separatorVar,
                                             value=",")
        self.semicolonRadioBut = ttk.Radiobutton(self.separatorFrame,
                                                 text="Semicolon",
                                                 variable=self.separatorVar,
                                                 value=";")
        self.tabRadioBut = ttk.Radiobutton(self.separatorFrame,
                                           text="Tab",
                                           variable=self.separatorVar,
                                           value="\t")

        self.commaRadioBut.grid(row=0, padx=2, pady=2, sticky=W)
        self.semicolonRadioBut.grid(row=1, padx=2, pady=2, sticky=W)
        self.tabRadioBut.grid(row=2, padx=2, pady=2, sticky=W)

        # save filename as full path
        self.saveFilenameAs = RadioFrame(
            self,
            text="Save (show) filename as:",
            optionName="SaveFullPath",
            default="Basename",
            options=["Basename", "Full path", "Unique path"])

        # selection of directories
        self.directoriesFrame = ttk.Frame(self)
        self.directoriesFrame.columnconfigure(0, weight=1)
        self.directoryOptions = [
            ("Default directory for file selection", "FileDirectory",
             os.getcwd()),
            ("Default directory for results", "ResultDirectory", os.getcwd()),
            ("Directory for saving of processing logs", "LogDirectory",
             os.path.join(os.getcwd(), "Stuff", "Logs")),
            ("Directory for images", "ImageDirectory", os.getcwd()),
            ("Directory for saving of selected files",
             "SelectedFilesDirectory",
             os.path.join(os.getcwd(), "Stuff", "Selected files"))
        ]
        for count, option in enumerate(self.directoryOptions):
            exec(
                """self.{1} = ChooseDirectoryFrame(self.directoriesFrame, '{0}', '{1}', \
                 r'{2}')""".format(*option))
            exec(
                "self.{}.grid(row = {}, column = 0, pady = 2, padx = 2, sticky = (E, W))"
                .format(option[1], count))

        # default time
        self.timeLabFrame = ttk.Labelframe(self, text="Default time")
        self.timeFrame = TimeFrame(self.timeLabFrame)
        self.timeFrame.grid(row=0, column=0)

        # processor options
        self.processorOptions = OptionFrame(self,
                                            text="Default process options")

        # checking messages
        self.messageCheckingFrame = ttk.Labelframe(
            self, text="Messages and new versions")
        self.messageCheckingVar = BooleanVar()
        self.messageCheckingVar.set(optionGet("CheckMessages", True, "bool"))
        self.messageCheckingChB = ttk.Checkbutton(
            self.messageCheckingFrame,
            variable=self.messageCheckingVar,
            onvalue=True,
            offvalue=False,
            text="Check messages and new versions")
        self.messageCheckingChB.grid(column=0, row=0)

        # buttons
        self.buttonFrame = ttk.Frame(self)
        self.buttonFrame.columnconfigure(1, weight=1)

        self.saveBut = ttk.Button(self.buttonFrame,
                                  text="Save",
                                  command=self.saveFun)
        self.okBut = ttk.Button(self.buttonFrame,
                                text="Ok",
                                command=self.okFun)
        self.cancelBut = ttk.Button(self.buttonFrame,
                                    text="Cancel",
                                    command=self.cancelFun)

        self.saveBut.grid(column=0, row=0, padx=3, pady=2, sticky=(W))
        self.okBut.grid(column=1, row=0, padx=3, pady=2)
        self.cancelBut.grid(column=2, row=0, padx=3, pady=2, sticky=(E))

        # grid of self contents
        self.parametersF.grid(row=0,
                              column=0,
                              columnspan=4,
                              sticky=(N, W),
                              padx=4,
                              pady=2)
        self.fileTypeFrame.grid(row=2,
                                column=0,
                                columnspan=2,
                                padx=3,
                                pady=4,
                                sticky=(W, N, E, S))
        self.buttonFrame.grid(row = 8, column = 0, columnspan = 4, padx = 3, pady = 4,\
                              sticky = (E, W, N, S))
        self.separatorFrame.grid(row=3,
                                 column=0,
                                 columnspan=2,
                                 padx=3,
                                 pady=4,
                                 sticky=(W, N, E))
        self.saveFilenameAs.grid(row=2,
                                 column=2,
                                 padx=3,
                                 pady=4,
                                 sticky=(N, W, E))
        self.directoriesFrame.grid(row=5,
                                   column=0,
                                   columnspan=5,
                                   padx=3,
                                   pady=8,
                                   sticky=(N, W, E))
        self.timeLabFrame.grid(row=2, column=3, padx=3, pady=4, sticky=(N, W))
        self.processorOptions.grid(row=3,
                                   column=2,
                                   pady=4,
                                   padx=4,
                                   sticky=(N, W),
                                   columnspan=2,
                                   rowspan=2)
        self.messageCheckingFrame.grid(row=4,
                                       column=0,
                                       columnspan=2,
                                       sticky=(N, W),
                                       pady=3,
                                       padx=3)

    def saveFun(self):
        "saves all options"
        for parameter in Parameters().parameters:
            optionWrite(parameter[4], bool(eval(("self.parametersF." +\
                                                 parameter[0].replace(" ", "") + "Var.get()"
                                                 ))))
        optionWrite("DefProcessOutputFileType",
                    "'" + self.fileTypeVar.get() + "'")
        optionWrite("SaveFullPath", self.saveFilenameAs.get())
        optionWrite("ResultSeparator", "'" + self.separatorVar.get() + "'")
        optionWrite("DefStartTime", self.timeFrame.startTimeVar.get())
        optionWrite("DefStopTime", self.timeFrame.timeVar.get())
        optionWrite("ProcessWhat",
                    "'" + self.processorOptions.processWhat.get() + "'")
        optionWrite(
            "RemoveReflectionsWhere",
            "'" + self.processorOptions.removeReflectionsWhere.get() + "'")
        optionWrite("DefSaveTags", self.processorOptions.saveTags.get())
        optionWrite("DefClearFilesAfterProcessing",
                    self.processorOptions.clearFilesAfterProcessing.get())
        optionWrite("CheckMessages", bool(self.messageCheckingVar.get()))
        for option in self.directoryOptions:
            directory = eval("self.{}.get()".format(option[1])).rstrip("\/")
            if os.path.exists(directory):
                optionWrite(option[1], "r'" + directory + "'")
            else:
                messagebox.showinfo(message="Directory " + directory +
                                    " does not exist.",
                                    icon="error",
                                    parent=self,
                                    title="Error",
                                    detail="Choose an existing directory.")
                return False
        return True

    def okFun(self):
        "saves options and exits"
        if self.saveFun():
            self.destroy()

    def cancelFun(self):
        "destroys the window"
        self.destroy()
コード例 #7
0
ファイル: options.py プロジェクト: bahniks/CM_Manager_0_3_4
    def __init__(self, root):
        super().__init__(root)
        self.title("Options")
        self.grab_set()
        self.focus_set()
        self.resizable(FALSE, FALSE)
        placeWindow(self, 824, 844)
        self["padx"] = 10
        self["pady"] = 10

        self.parametersF = ParameterFrame(self, "Default parameters")

        # default filetype of processor output
        self.fileTypeVar = StringVar()
        self.fileTypeVar.set(
            optionGet("DefProcessOutputFileType", ".txt", "str"))

        self.fileTypeFrame = ttk.Labelframe(self,
                                            text="Default output filetype")

        self.txtRadioBut = ttk.Radiobutton(self.fileTypeFrame,
                                           text=".txt",
                                           variable=self.fileTypeVar,
                                           value=".txt")
        self.csvRadioBut = ttk.Radiobutton(self.fileTypeFrame,
                                           text=".csv",
                                           variable=self.fileTypeVar,
                                           value=".csv")

        self.txtRadioBut.grid(row=1, column=0, padx=2, pady=2, sticky=W)
        self.csvRadioBut.grid(row=0, column=0, padx=2, pady=2, sticky=W)

        # output separator
        self.separatorVar = StringVar()
        self.separatorVar.set(optionGet("ResultSeparator", ",", "str"))

        self.separatorFrame = ttk.Labelframe(self, text="Result separator")

        self.commaRadioBut = ttk.Radiobutton(self.separatorFrame,
                                             text="Comma",
                                             variable=self.separatorVar,
                                             value=",")
        self.semicolonRadioBut = ttk.Radiobutton(self.separatorFrame,
                                                 text="Semicolon",
                                                 variable=self.separatorVar,
                                                 value=";")
        self.tabRadioBut = ttk.Radiobutton(self.separatorFrame,
                                           text="Tab",
                                           variable=self.separatorVar,
                                           value="\t")

        self.commaRadioBut.grid(row=0, padx=2, pady=2, sticky=W)
        self.semicolonRadioBut.grid(row=1, padx=2, pady=2, sticky=W)
        self.tabRadioBut.grid(row=2, padx=2, pady=2, sticky=W)

        # save filename as full path
        self.saveFilenameAs = RadioFrame(
            self,
            text="Save (show) filename as:",
            optionName="SaveFullPath",
            default="Basename",
            options=["Basename", "Full path", "Unique path"])

        # selection of directories
        self.directoriesFrame = ttk.Frame(self)
        self.directoriesFrame.columnconfigure(0, weight=1)
        self.directoryOptions = [
            ("Default directory for file selection", "FileDirectory",
             os.getcwd()),
            ("Default directory for results", "ResultDirectory", os.getcwd()),
            ("Directory for saving of processing logs", "LogDirectory",
             os.path.join(os.getcwd(), "Stuff", "Logs")),
            ("Directory for images", "ImageDirectory", os.getcwd()),
            ("Directory for saving of selected files",
             "SelectedFilesDirectory",
             os.path.join(os.getcwd(), "Stuff", "Selected files"))
        ]
        for count, option in enumerate(self.directoryOptions):
            exec(
                """self.{1} = ChooseDirectoryFrame(self.directoriesFrame, '{0}', '{1}', \
                 r'{2}')""".format(*option))
            exec(
                "self.{}.grid(row = {}, column = 0, pady = 2, padx = 2, sticky = (E, W))"
                .format(option[1], count))

        # default time
        self.timeLabFrame = ttk.Labelframe(self, text="Default time")
        self.timeFrame = TimeFrame(self.timeLabFrame)
        self.timeFrame.grid(row=0, column=0)

        # processor options
        self.processorOptions = OptionFrame(self,
                                            text="Default process options")

        # checking messages
        self.messageCheckingFrame = ttk.Labelframe(
            self, text="Messages and new versions")
        self.messageCheckingVar = BooleanVar()
        self.messageCheckingVar.set(optionGet("CheckMessages", True, "bool"))
        self.messageCheckingChB = ttk.Checkbutton(
            self.messageCheckingFrame,
            variable=self.messageCheckingVar,
            onvalue=True,
            offvalue=False,
            text="Check messages and new versions")
        self.messageCheckingChB.grid(column=0, row=0)

        # buttons
        self.buttonFrame = ttk.Frame(self)
        self.buttonFrame.columnconfigure(1, weight=1)

        self.saveBut = ttk.Button(self.buttonFrame,
                                  text="Save",
                                  command=self.saveFun)
        self.okBut = ttk.Button(self.buttonFrame,
                                text="Ok",
                                command=self.okFun)
        self.cancelBut = ttk.Button(self.buttonFrame,
                                    text="Cancel",
                                    command=self.cancelFun)

        self.saveBut.grid(column=0, row=0, padx=3, pady=2, sticky=(W))
        self.okBut.grid(column=1, row=0, padx=3, pady=2)
        self.cancelBut.grid(column=2, row=0, padx=3, pady=2, sticky=(E))

        # grid of self contents
        self.parametersF.grid(row=0,
                              column=0,
                              columnspan=4,
                              sticky=(N, W),
                              padx=4,
                              pady=2)
        self.fileTypeFrame.grid(row=2,
                                column=0,
                                columnspan=2,
                                padx=3,
                                pady=4,
                                sticky=(W, N, E, S))
        self.buttonFrame.grid(row = 8, column = 0, columnspan = 4, padx = 3, pady = 4,\
                              sticky = (E, W, N, S))
        self.separatorFrame.grid(row=3,
                                 column=0,
                                 columnspan=2,
                                 padx=3,
                                 pady=4,
                                 sticky=(W, N, E))
        self.saveFilenameAs.grid(row=2,
                                 column=2,
                                 padx=3,
                                 pady=4,
                                 sticky=(N, W, E))
        self.directoriesFrame.grid(row=5,
                                   column=0,
                                   columnspan=5,
                                   padx=3,
                                   pady=8,
                                   sticky=(N, W, E))
        self.timeLabFrame.grid(row=2, column=3, padx=3, pady=4, sticky=(N, W))
        self.processorOptions.grid(row=3,
                                   column=2,
                                   pady=4,
                                   padx=4,
                                   sticky=(N, W),
                                   columnspan=2,
                                   rowspan=2)
        self.messageCheckingFrame.grid(row=4,
                                       column=0,
                                       columnspan=2,
                                       sticky=(N, W),
                                       pady=3,
                                       padx=3)
コード例 #8
0
ファイル: tools.py プロジェクト: bahniks/CM_Manager_0_3_5
class SetBatchTime(Toplevel):
    "toplevel window where time is chosen for batch processing of files with different times"
    def __init__(self, root):
        super().__init__(root)

        self.root = root
        placeWindow(self, 598, 208)
        self.title = "Set batch time"
        self.grab_set()
        self.focus_set()     
        self.resizable(False, False)

        self.batchTime = optionGet("LastBatchTime", "[(0, 20)]", "list")
        self.developer = optionGet("Developer", False, 'bool')
        self.manualChangeEnabled = self.developer

        # frames
        self.buttonFrame = ttk.Frame(self)
        self.removeFrame = ttk.Frame(self)
        self.timeFrame = TimeFrame(self, observe = False)

        # buttons
        self.okBut = ttk.Button(self, text = "Ok", command = self.okFun)
        self.closeBut = ttk.Button(self, text = "Close", command = self.destroy)
        self.addBut = ttk.Button(self.buttonFrame, text = "Add", command = self.addFun, width = 8)
        self.removeLastBut = ttk.Button(self.removeFrame , text = "Remove last",
                                        command = self.removeLastFun)
        self.resetBut = ttk.Button(self.removeFrame , text = "Reset", command = self.resetFun)
        self.clearBut = ttk.Button(self.removeFrame , text = "Clear", command = self.clearFun)

        # text
        self.text = Text(self, height = 5, wrap = "word", width = 73)
        self.text.insert("1.0", self.batchTime)
        self.text.bind("<3>", lambda e: self.popUp(e))
        if not self.developer:
            self.text["state"] = "disabled"
            self.text["background"] = self._color()
        else:
            self.addBut["state"] = "disabled"
            self.removeLastBut["state"] = "disabled"
            
        # adding to grid
        self.buttonFrame.grid(column = 1, row = 0, sticky = W, pady = 2)
        self.removeFrame.grid(column = 3, row = 0, pady = 3)
        self.timeFrame.grid(column = 0, row = 0)
        
        self.okBut.grid(column = 3, row = 2, pady = 2)
        self.closeBut.grid(column = 2, row = 2, pady = 2)
        self.addBut.grid(column = 0, row = 2, columnspan = 2)
        self.removeLastBut.grid(column = 0, row = 0, pady = 0)
        self.resetBut.grid(column = 0, row = 1, pady = 2)
        self.clearBut.grid(column = 0, row = 2, pady = 0)

        self.text.grid(column = 0, row = 1, columnspan = 4, pady = 5, padx = 5)

        # +x buttons
        ttk.Button(self.buttonFrame, text = "+1", command = lambda: self.addTime(1),
                   width = 3).grid(column = 0, row = 0)
        ttk.Button(self.buttonFrame, text = "+2", command = lambda: self.addTime(2),
                   width = 3).grid(column = 1, row = 0)
        ttk.Button(self.buttonFrame, text = "+5", command = lambda: self.addTime(5),
                   width = 3).grid(column = 0, row = 1)
        ttk.Button(self.buttonFrame, text = "+10", command = lambda: self.addTime(10),
                   width = 3).grid(column = 1, row = 1)


    def _color(self):
        return "grey94"
        
    def okFun(self):
        "closes the window and saves the selected batch time to root's batch time"
        if not self._checkText():
            return
        self.root.selectedBatchTime = self.batchTime
        optionWrite("LastBatchTime", self.batchTime)            
        self.destroy()

    def addFun(self):
        "adds selected time to the text widget as well as to the selected batch time"
        start = int(self.timeFrame.startTimeVar.get())
        end = int(self.timeFrame.timeVar.get())
        newTime = (start, end)
        self.batchTime.append(newTime)
        self._updateText()

    def _updateText(self):
        "updates the text widget"
        state = self.text["state"]
        self.text["state"] = "normal"
        self.text.delete("1.0", "end")
        self.text.insert("1.0", self.batchTime) 
        self.text["state"] = state

    def removeLastFun(self):
        "removes the last added time"
        if self.batchTime:
            self.batchTime.pop()
        self._updateText() 

    def resetFun(self):
        "resets the text to last batch time used (obtained from options)"
        self.batchTime = optionGet("LastBatchTime", "[(0, 20)]", "list")
        self._updateText()

    def clearFun(self):
        "clears the text"
        self.batchTime = []
        self._updateText()

    def popUp(self, event):
        "pop-up menu for text widget"
        menu = Menu(self, tearoff = 0)
        if self.manualChangeEnabled:
            menu.add_command(label = "Disable manual change", command = self.disableManualChange)
        else:
            menu.add_command(label = "Enable manual change", command = self.enableManualChange)
        menu.post(event.x_root, event.y_root)

    def enableManualChange(self):
        "enables manual text changes"
        self.manualChangeEnabled = True
        self.text["state"] = "normal"
        self.text["background"] = "white"
        self.addBut["state"] = "disabled"
        self.removeLastBut["state"] = "disabled"

    def _checkText(self):
        "checks whether the text is in right format"
        try:
            self.batchTime = eval(self.text.get('1.0', 'end'))
            if not isinstance(self.batchTime, list):
                raise Exception("Selected time must be a list.")
            for pair in self.batchTime:
                if not isinstance(pair, tuple):
                    raise Exception("{} is not a tuple.".format(pair))
                if len(pair) != 2:
                    raise Exception("{} has more than two items (needs exactly two).".format(pair))
                if not isinstance(pair[0], int):
                    raise Exception("{} is not an integer.".format(pair[0]))
                if not isinstance(pair[1], int):
                    raise Exception("{} is not an integer.".format(pair[1]))
                if pair[0] >= pair[1]:
                    raise Exception("The first item in every pair must be lower than the second.")
        except Exception as e:
            messagebox.showinfo(message = "There is an error in the selected batch time.\n"
                                "Correct it or use Reset or Clear buttons.", detail = e,
                                title = "Error in selected time", icon = "error")
            return False
        else:
            return True
        
    def disableManualChange(self):
        "disables manual text changes"
        if not self._checkText():
            return
        self.manualChangeEnabled = False
        self.text["state"] = "disabled"
        self.text["background"] = self._color()
        self.addBut["state"] = "normal"
        self.removeLastBut["state"] = "normal"

    def addTime(self, x):
        "adds time to start and stop time in timeFrame"
        start = int(self.timeFrame.startTimeVar.get()) + x
        end = int(self.timeFrame.timeVar.get()) + x
        self.timeFrame.startTimeVar.set(str(start))
        self.timeFrame.timeVar.set(str(end))        
コード例 #9
0
ファイル: tools.py プロジェクト: bahniks/CM_Manager_0_3_5
    def __init__(self, root):
        super().__init__(root)

        self.root = root
        placeWindow(self, 598, 208)
        self.title = "Set batch time"
        self.grab_set()
        self.focus_set()     
        self.resizable(False, False)

        self.batchTime = optionGet("LastBatchTime", "[(0, 20)]", "list")
        self.developer = optionGet("Developer", False, 'bool')
        self.manualChangeEnabled = self.developer

        # frames
        self.buttonFrame = ttk.Frame(self)
        self.removeFrame = ttk.Frame(self)
        self.timeFrame = TimeFrame(self, observe = False)

        # buttons
        self.okBut = ttk.Button(self, text = "Ok", command = self.okFun)
        self.closeBut = ttk.Button(self, text = "Close", command = self.destroy)
        self.addBut = ttk.Button(self.buttonFrame, text = "Add", command = self.addFun, width = 8)
        self.removeLastBut = ttk.Button(self.removeFrame , text = "Remove last",
                                        command = self.removeLastFun)
        self.resetBut = ttk.Button(self.removeFrame , text = "Reset", command = self.resetFun)
        self.clearBut = ttk.Button(self.removeFrame , text = "Clear", command = self.clearFun)

        # text
        self.text = Text(self, height = 5, wrap = "word", width = 73)
        self.text.insert("1.0", self.batchTime)
        self.text.bind("<3>", lambda e: self.popUp(e))
        if not self.developer:
            self.text["state"] = "disabled"
            self.text["background"] = self._color()
        else:
            self.addBut["state"] = "disabled"
            self.removeLastBut["state"] = "disabled"
            
        # adding to grid
        self.buttonFrame.grid(column = 1, row = 0, sticky = W, pady = 2)
        self.removeFrame.grid(column = 3, row = 0, pady = 3)
        self.timeFrame.grid(column = 0, row = 0)
        
        self.okBut.grid(column = 3, row = 2, pady = 2)
        self.closeBut.grid(column = 2, row = 2, pady = 2)
        self.addBut.grid(column = 0, row = 2, columnspan = 2)
        self.removeLastBut.grid(column = 0, row = 0, pady = 0)
        self.resetBut.grid(column = 0, row = 1, pady = 2)
        self.clearBut.grid(column = 0, row = 2, pady = 0)

        self.text.grid(column = 0, row = 1, columnspan = 4, pady = 5, padx = 5)

        # +x buttons
        ttk.Button(self.buttonFrame, text = "+1", command = lambda: self.addTime(1),
                   width = 3).grid(column = 0, row = 0)
        ttk.Button(self.buttonFrame, text = "+2", command = lambda: self.addTime(2),
                   width = 3).grid(column = 1, row = 0)
        ttk.Button(self.buttonFrame, text = "+5", command = lambda: self.addTime(5),
                   width = 3).grid(column = 0, row = 1)
        ttk.Button(self.buttonFrame, text = "+10", command = lambda: self.addTime(10),
                   width = 3).grid(column = 1, row = 1)
コード例 #10
0
ファイル: processor.py プロジェクト: bahniks/CM_Manager_0_3_4
class Processor(ttk.Frame):
    "represents 'Process' page in the main window notebook"

    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (10, 10, 12, 12)
        self.root = root  # potreba pouze pro progressbar

        # variables
        self.status = StringVar()

        # frames
        self.parametersF = ParameterFrame(self)
        self.fileStorageFrame = FileStorageFrame(self)
        self.saveToFrame = SaveToFrame(self, parent="processor")
        self.timeFrame = TimeFrame(self)
        self.optionFrame = OptionFrame(self, text="Options")

        # buttons
        self.process = ttk.Button(self,
                                  text="Process Files",
                                  command=self.processFun,
                                  state="disabled")

        # labels
        self.statusBar = ttk.Label(self, textvariable=self.status)

        # adding to grid
        self.parametersF.grid(column=0,
                              row=3,
                              columnspan=4,
                              sticky=(N, W),
                              padx=4)
        self.fileStorageFrame.grid(column=3, row=0, pady=5, padx=4)
        self.timeFrame.grid(column=1, row=5, padx=30, pady=15, sticky=(N, W))

        self.process.grid(column=3, row=7, sticky=(S, E), padx=4, pady=3)

        self.statusBar.grid(column=0,
                            row=7,
                            columnspan=3,
                            sticky=(N, S, E, W),
                            padx=6,
                            pady=3)

        self.saveToFrame.grid(column=1,
                              row=1,
                              columnspan=3,
                              sticky=(N, S, E, W),
                              padx=6,
                              pady=2)

        self.optionFrame.grid(column=0, row=5, sticky=(N, E), padx=6)

        # what should be enlarged
        self.columnconfigure(2, weight=1)
        self.rowconfigure(2, weight=3)
        self.rowconfigure(4, weight=2)
        self.rowconfigure(6, weight=2)

    def processCheck(self):
        "checks whether all inputs are valid - helper function for processFun"

        if self.saveToFrame.saveToVar.get() == "":
            raise Exception("You have to choose an output file!")

        if len(self.root.fileStorage.arenafiles) == 0:
            raise Exception("You haven't chosen any file!")

        try:
            startTime = float(self.timeFrame.startTimeVar.get())
        except Exception:
            raise Exception("Start time has to be a number!")
        try:
            time = float(self.timeFrame.timeVar.get())
        except Exception:
            raise Exception("Stop time has to be a number!")

        if startTime >= time:
            raise Exception("Start time must be smaller than stop time!")

        if time < 0 or startTime < 0:
            raise Exception("Time has to be set to a positive value")

        if not os.path.exists(
                os.path.split(self.saveToFrame.saveToVar.get())[0]):
            if os.path.split(self.saveToFrame.saveToVar.get())[0]:
                raise Exception("Pathname of the output file doesn't exist!")

    def processFun(self):
        "processes chosen files and saves the results in the save-to file"
        # checking for mistakes
        try:
            self.processCheck()
        except Exception as e:
            self.bell()
            self.status.set(e)
            return

        # files to be processed
        self.filesToProcess = [file for file in self.root.fileStorage.arenafiles if \
                               self.optionFrame.processFile(file)]

        # progressWindow and check for number of files for processing
        if len(self.filesToProcess) > 1:
            self.stoppedProcessing = False
            self.progressWindow = ProgressWindow(self,
                                                 len(self.filesToProcess))
        elif len(self.filesToProcess) == 0:
            self.bell()
            self.status.set("There is no file selected for processing!")
            return

        # selected methods
        methods = []
        for method in Parameters().parameters:
            if eval("self.parametersF.%sVar.get()" %
                    (method[0].replace(" ", ""))):
                methods.append(method[0])

        output = self.saveToFrame.saveToVar.get()
        startTime = float(self.timeFrame.startTimeVar.get())
        time = float(self.timeFrame.timeVar.get())
        separator = optionGet("ResultSeparator", ",", "str")

        results = separator.join(["File"] + methods)

        if self.optionFrame.saveTags.get():
            results += separator + "Tags"

        self.log = Log(methods, startTime, time, self.filesToProcess,
                       self.root.fileStorage,
                       self.optionFrame.removeReflectionsWhere.get(), output)
        self.someProblem = False

        developer = optionGet("Developer", False, 'bool')

        for file in self.filesToProcess:
            # loading of cm object
            if methods:
                try:
                    if file in self.root.fileStorage.pairedfiles:
                        cm = CM(file,
                                nameR=self.root.fileStorage.pairedfiles[file])
                    else:
                        cm = CM(file, nameR="auto")

                    if self.optionFrame.removeReflections(file):
                        cm.removeReflections(
                            points=self.root.fileStorage.reflections.get(
                                file, None))
                except Exception as e:
                    if developer:
                        print(e)
                    filename = returnName(
                        filename=file,
                        allFiles=self.root.fileStorage.arenafiles)
                    results += "\n" + filename + "{}NA".format(
                        separator) * len(methods)
                    self.log.failedToLoad.append(file)
                    self.someProblem = True
                    continue

            result = []
            for method in Parameters().parameters:
                if method[0] in methods:
                    try:
                        if method[2] == "custom":
                            exec("from Stuff.Parameters import {}".format(
                                method[5]))
                        result.append(eval(method[1]))
                    except Exception as e:
                        if developer:
                            print(e)
                        result.append("NA")
                        self.log.methodProblems[method[0]].append(file)
                        self.someProblem = True

            result = separator.join(map(str, result))
            if methods:
                result = separator + result
            filename = returnName(filename=file,
                                  allFiles=self.root.fileStorage.arenafiles)
            results += "\n" + filename + result

            if self.optionFrame.saveTags.get():  # tag inclusion in results
                if file in self.root.fileStorage.tagged:
                    results += separator + "1"
                else:
                    results += separator + "0"

            if len(self.filesToProcess) > 1:
                if self.stoppedProcessing:
                    writeResults(output, results)
                    self.log.stopped = file
                    self.log.writeLog()
                    self.status.set("Processing stopped")
                    return
                else:
                    self.progressWindow.addOne()

        writeResults(output, results)
        self.log.writeLog()

        # change of status bar and closing of progressWindow
        if len(self.filesToProcess) > 1:
            if self.someProblem:
                self.status.set("Files were processed.")
            else:
                self.status.set("Files were processed successfully.")
            self.progressWindow.destroy()
        else:
            if self.someProblem:
                self.status.set("File was processed.")
            else:
                self.status.set("File was processed successfully.")

        # removal of files from fileStorage if selected
        if self.optionFrame.clearFilesAfterProcessing.get():
            for file in self.filesToProcess:
                self.root.fileStorage.arenafiles.remove(file)
            self.fileStorageFrame.chosenVar.set(
                len(self.root.fileStorage.arenafiles))
            if not self.root.fileStorage.arenafiles:
                self.fileStorageFrame.removeFiles.state(["disabled"])
                self.process.state(["disabled"])

        if self.someProblem:
            ProcessingProblemDialog(self, self.log.filename)

    def checkProcessing(self):
        "method updating page after change of notebook tab"
        if self.root.fileStorage.arenafiles and self.saveToFrame.saveToVar.get(
        ):
            self.process.state(["!disabled"])
        else:
            self.process.state(["disabled"])

        if self.root.fileStorage.arenafiles or self.root.fileStorage.wrongfiles:
            self.fileStorageFrame.removeFiles.state(["!disabled"])
        else:
            self.fileStorageFrame.removeFiles.state(["disabled"])

        self.fileStorageFrame.chosenVar.set(
            len(self.root.fileStorage.arenafiles))
        self.fileStorageFrame.nonMatchingVar.set(
            len(self.root.fileStorage.wrongfiles))
コード例 #11
0
ファイル: options.py プロジェクト: bahniks/CM_Manager_0_3_4
    def __init__(self, root):
        super().__init__(root)
        self.title("Options")
        self.grab_set()
        self.focus_set()
        self.resizable(FALSE, FALSE)
        placeWindow(self, 824, 844)
        self["padx"] = 10
        self["pady"] = 10
        
        self.parametersF = ParameterFrame(self, "Default parameters")

        # default filetype of processor output
        self.fileTypeVar = StringVar()
        self.fileTypeVar.set(optionGet("DefProcessOutputFileType", ".txt", "str"))

        self.fileTypeFrame = ttk.Labelframe(self, text = "Default output filetype")

        self.txtRadioBut = ttk.Radiobutton(self.fileTypeFrame, text = ".txt",
                                           variable = self.fileTypeVar, value = ".txt")
        self.csvRadioBut = ttk.Radiobutton(self.fileTypeFrame, text = ".csv",
                                           variable = self.fileTypeVar, value = ".csv")
        
        self.txtRadioBut.grid(row = 1, column = 0, padx = 2, pady = 2, sticky = W)
        self.csvRadioBut.grid(row = 0, column = 0, padx = 2, pady = 2, sticky = W)

        # output separator
        self.separatorVar = StringVar()
        self.separatorVar.set(optionGet("ResultSeparator", ",", "str"))

        self.separatorFrame = ttk.Labelframe(self, text = "Result separator")

        self.commaRadioBut = ttk.Radiobutton(self.separatorFrame, text = "Comma",
                                             variable = self.separatorVar, value = ",")
        self.semicolonRadioBut = ttk.Radiobutton(self.separatorFrame, text = "Semicolon",
                                                 variable = self.separatorVar, value = ";")        
        self.tabRadioBut = ttk.Radiobutton(self.separatorFrame, text = "Tab",
                                           variable = self.separatorVar, value = "\t")
        
        self.commaRadioBut.grid(row = 0, padx = 2, pady = 2, sticky = W)
        self.semicolonRadioBut.grid(row = 1, padx = 2, pady = 2, sticky = W)
        self.tabRadioBut.grid(row = 2, padx = 2, pady = 2, sticky = W)

        # save filename as full path
        self.saveFilenameAs = RadioFrame(self, text = "Save (show) filename as:",
                                         optionName = "SaveFullPath", default = "Basename",
                                         options = ["Basename", "Full path", "Unique path"])

        # selection of directories
        self.directoriesFrame = ttk.Frame(self)
        self.directoriesFrame.columnconfigure(0, weight = 1)
        self.directoryOptions = [
            ("Default directory for file selection", "FileDirectory", os.getcwd()),
            ("Default directory for results", "ResultDirectory", os.getcwd()),
            ("Directory for saving of processing logs", "LogDirectory",
             os.path.join(os.getcwd(), "Stuff", "Logs")),
            ("Directory for images", "ImageDirectory", os.getcwd()),
            ("Directory for saving of selected files", "SelectedFilesDirectory",
             os.path.join(os.getcwd(), "Stuff", "Selected files"))]
        for count, option in enumerate(self.directoryOptions):
            exec("""self.{1} = ChooseDirectoryFrame(self.directoriesFrame, '{0}', '{1}', \
                 r'{2}')""".format(*option))
            exec("self.{}.grid(row = {}, column = 0, pady = 2, padx = 2, sticky = (E, W))".format(
                option[1], count))

        # default time
        self.timeLabFrame = ttk.Labelframe(self, text = "Default time")
        self.timeFrame = TimeFrame(self.timeLabFrame)
        self.timeFrame.grid(row = 0, column = 0)

        # processor options
        self.processorOptions = OptionFrame(self, text = "Default process options")

        # checking messages
        self.messageCheckingFrame = ttk.Labelframe(self, text = "Messages and new versions")
        self.messageCheckingVar = BooleanVar()
        self.messageCheckingVar.set(optionGet("CheckMessages", True, "bool"))
        self.messageCheckingChB = ttk.Checkbutton(self.messageCheckingFrame,
                                                  variable = self.messageCheckingVar,
                                                  onvalue = True, offvalue = False,
                                                  text = "Check messages and new versions")
        self.messageCheckingChB.grid(column = 0, row = 0)
        
        # buttons
        self.buttonFrame = ttk.Frame(self)
        self.buttonFrame.columnconfigure(1, weight = 1)

        self.saveBut = ttk.Button(self.buttonFrame, text = "Save", command = self.saveFun)
        self.okBut = ttk.Button(self.buttonFrame, text = "Ok", command = self.okFun)
        self.cancelBut = ttk.Button(self.buttonFrame, text = "Cancel", command = self.cancelFun)

        self.saveBut.grid(column = 0, row = 0, padx = 3, pady = 2, sticky = (W))
        self.okBut.grid(column = 1, row = 0, padx = 3, pady = 2)
        self.cancelBut.grid(column = 2, row = 0, padx = 3, pady = 2, sticky = (E))

        # grid of self contents        
        self.parametersF.grid(row = 0, column = 0, columnspan = 4, sticky = (N, W), padx = 4,
                              pady = 2)
        self.fileTypeFrame.grid(row = 2, column = 0, columnspan = 2, padx = 3, pady = 4,
                                sticky = (W, N, E, S))
        self.buttonFrame.grid(row = 8, column = 0, columnspan = 4, padx = 3, pady = 4,\
                              sticky = (E, W, N, S))
        self.separatorFrame.grid(row = 3, column = 0, columnspan = 2, padx = 3, pady = 4,
                                 sticky = (W, N, E))
        self.saveFilenameAs.grid(row = 2, column = 2, padx = 3, pady = 4, sticky = (N, W, E))
        self.directoriesFrame.grid(row = 5, column = 0, columnspan = 5, padx = 3, pady = 8,
                                   sticky = (N, W, E))
        self.timeLabFrame.grid(row = 2, column = 3, padx = 3, pady = 4, sticky = (N, W))
        self.processorOptions.grid(row = 3, column = 2, pady = 4, padx = 4, sticky = (N, W),
                                   columnspan = 2, rowspan = 2)
        self.messageCheckingFrame.grid(row = 4, column = 0, columnspan = 2, sticky = (N, W),
                                       pady = 3, padx = 3)
コード例 #12
0
    def __init__(self, root, files, controlled=False):
        super().__init__(root)

        self.rowconfigure(0, weight=1)

        self.allFiles = files  # used when un-selecting files
        self.files = files  # currently diplayed files
        self.controlled = controlled  # True if FileTree called from controller
        self.root = root
        self.fileStorage = self.root.fileStorage
        self.index = self.root.index  # which file is selected when the FileTree is initialized
        self.usedProblemOrder = -1  # by which method is the tree ordered (index)

        # tree
        self.treeFrame = ttk.Frame(self)
        self.treeFrame.grid(column=0, row=0, columnspan=3, sticky=(N, S, E, W))
        self.treeFrame.rowconfigure(0, weight=1)
        self.treeFrame.columnconfigure(0, weight=1)

        self.tree = ttk.Treeview(self.treeFrame,
                                 selectmode="browse",
                                 height=20)
        self.tree.grid(column=0, row=0, sticky=(N, S, E, W))

        if self.controlled:
            columns = ("problem", "tag")
        else:
            columns = ("tag")
        self.tree["columns"] = columns

        self.tree.column("#0", width=240, anchor="w")
        self.tree.heading("#0", text="File", command=self.orderByNames)

        self.tree.column("tag", width=40, anchor="center")
        self.tree.heading("tag", text="Tag", command=self.orderByTag)

        if self.controlled:
            self.tree.column("problem", width=160, anchor="e")
            self.tree.heading("problem",
                              text="Problems",
                              command=self.orderByProblem)

        self.scrollbar = ttk.Scrollbar(self.treeFrame,
                                       orient=VERTICAL,
                                       command=self.tree.yview)
        self.scrollbar.grid(column=1, row=0, sticky=(N, S, E))
        self.tree.configure(yscrollcommand=self.scrollbar.set)

        self.tree.bind("<1>", lambda e: self.click(e))
        self.tree.bind("<3>", lambda e: self.popUp(e))

        self.tree.tag_configure("comment", background=commentColor())

        self.drawTree()

        # bottom frame
        self.bottomFrame = ttk.Frame(self)
        self.bottomFrame.grid(column=0, row=1, columnspan=2)
        self.bottomFrame.columnconfigure(3, weight=1)
        self.bottomFrame.rowconfigure(1, weight=1)

        # previous and next buttons
        self.fileLabFrame = ttk.Labelframe(self.bottomFrame, text="File")
        self.fileLabFrame.grid(column=0, row=0, sticky=(N, W), pady=3, padx=1)

        self.previousBut = ttk.Button(self.fileLabFrame,
                                      text="Previous",
                                      command=self.previousFun)
        self.previousBut.grid(column=0, row=0, padx=3)

        self.nextBut = ttk.Button(self.fileLabFrame,
                                  text="Next",
                                  command=self.nextFun)
        self.nextBut.grid(column=1, row=0, padx=3)

        # tag buttons
        self.tagLabFrame = ttk.Labelframe(self.bottomFrame, text="Tagging")
        self.tagLabFrame.grid(column=0,
                              row=1,
                              sticky=(N, W),
                              rowspan=2,
                              padx=1,
                              pady=4)

        self.tagBut = ttk.Button(self.tagLabFrame,
                                 text="Tag file",
                                 command=self.tagFun)
        self.tagBut.grid(column=1, row=1, padx=3)
        self.checkTag()

        self.tagAllBut = ttk.Button(self.tagLabFrame,
                                    text="Tag all",
                                    command=self.tagAllFun)
        self.tagAllBut.grid(column=2, row=1, padx=3)

        self.untagAllBut = ttk.Button(self.tagLabFrame,
                                      text="Remove all tags",
                                      command=self.untagAllFun)
        self.untagAllBut.grid(column=3, row=1, padx=3)

        # time frame
        self.timeLabFrame = ttk.Labelframe(self.bottomFrame, text="Time")
        self.timeLabFrame.grid(column=3, row=0, rowspan=2, sticky=N, pady=3)
        self.timeLabFrame.root = self.root

        self.timeFrame = TimeFrame(self.timeLabFrame,
                                   onChange=True,
                                   observe=False)
        self.timeFrame.grid(column=0, row=0)
        self.timeFrame.timeVar.set(TimeFrame.stop)
        self.timeFrame.startTimeVar.set(TimeFrame.start)

        # remove reflections checkbutton
        self.removeReflectionsVar = BooleanVar()
        self.removeReflectionsVar.set(False)
        self.removeReflections = ttk.Checkbutton(
            self.bottomFrame,
            text="Remove reflections",
            variable=self.removeReflectionsVar,
            command=self.toggleReflections)
        self.removeReflections.grid(column=2,
                                    row=2,
                                    padx=7,
                                    pady=5,
                                    sticky=(N, W),
                                    columnspan=2)

        # frame radiobuttons
        self.frameFrame = ttk.Labelframe(self.bottomFrame, text="Frame")
        self.frameFrame.grid(column=2,
                             row=0,
                             padx=5,
                             rowspan=2,
                             pady=3,
                             sticky=N)

        self.frameVar = StringVar()
        self.frameVar.set("arena")

        self.arenaFrameRB = ttk.Radiobutton(self.frameFrame,
                                            text="Arena",
                                            variable=self.frameVar,
                                            value="arena",
                                            command=self.toggleFrame)
        self.arenaFrameRB.grid(column=0, row=0, pady=2)

        self.roomFrameRB = ttk.Radiobutton(self.frameFrame,
                                           text="Room",
                                           variable=self.frameVar,
                                           value="room",
                                           command=self.toggleFrame)
        self.roomFrameRB.grid(column=0, row=1, pady=2)
コード例 #13
0
class Controller(ttk.Frame):
    "represents 'Control' page in the main window notebook"
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (7, 7, 9, 9)

        self.root = root
        self.fileStorage = self.root.fileStorage

        # file selection
        self.saveToVar = StringVar()
        self.saveToVar.set(True)
        self.fileStorageFrame = FileStorageFrame(self)
        self.fileStorageFrame.grid(column = 1, row = 0, columnspan = 2, sticky = (N, S, E, W),
                                   pady = 5, padx = 2)

        # statusbar
        self.status = StringVar()
        
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.statusBar.grid(column = 0, row = 4, columnspan = 2, sticky = (S, E, W))
        
        # control button
        self.process = ttk.Button(self, text = "Control", command = self.controlFun)
        self.process.grid(column = 2, row = 4, sticky = E)
        self.process.state(["disabled"])
        
        # report
        self.reportFrame = ttk.LabelFrame(self, text = "Report")
        self.reportFrame.grid(column = 0, row = 0, rowspan = 4, sticky = (N, S, E, W), padx = 5)
        self.reportFrame.columnconfigure(0, weight = 1)
        self.reportFrame.rowconfigure(0, weight = 1)

        self.upFrame = ttk.Frame(self.reportFrame)
        self.upFrame.grid(column = 0, row = 0, columnspan = 2, sticky = (N, S, E, W))
        self.upFrame.columnconfigure(0, weight = 1)
        self.upFrame.rowconfigure(0, weight = 1)
        
        self.contentTree = ttk.Treeview(self.upFrame, selectmode = "none")
        self.contentTree.grid(column = 0, row = 0, sticky = (N, S, E, W))
        self.contentTree["columns"] = ("description", "importance", "tag")
        self.contentTree.column("#0", width = 250, anchor = "w")
        self.contentTree.heading("#0", text = "Problem",
                                 command = lambda: self.orderReport("name"))
        self.contentTree.column("description", width = 200, anchor = "e")
        self.contentTree.heading("description", text = "Description",
                                 command = lambda: self.orderReport("description"))
        self.contentTree.column("importance", width = 60, anchor = "e")
        self.contentTree.heading("importance", text = "Importance",
                                 command = lambda: self.orderReport("importance"))
        self.contentTree.column("tag", width = 10, anchor = "center")
        self.contentTree.heading("tag", text = "Tag", command = lambda: self.orderReport("tag"))
        self.scrollbar = ttk.Scrollbar(self.upFrame, orient = VERTICAL,
                                       command = self.contentTree.yview)
        self.scrollbar.grid(column = 1, row = 0, sticky = (N, S, E))
        self.contentTree.configure(yscrollcommand = self.scrollbar.set)
        
        self.saveToFrame = SaveToFrame(self.reportFrame, label = False)
        self.saveToFrame.grid(column = 0, row = 1, sticky = (E, W))

        self.saveBut = ttk.Button(self.reportFrame, text = "Save", command = self.saveFun)
        self.saveBut.grid(column = 1, row = 1, sticky = E, padx = 2)
    
        self.controlReport = ControlReport(self)
                       
        self.contentTree.tag_bind("file", "<Double-1>", lambda e: self.treeDoubleClick(e))
        self.contentTree.tag_bind("file", "<3>", lambda e: self.filePopUp(e))
        self.contentTree.tag_bind("ok", "<3>", lambda e: self.okPopUp(e))
        self.contentTree.tag_bind("control", "<3>", lambda e: self.controlPopUp(e))
        self.contentTree.tag_configure("comment", background = commentColor())
        
        # method selection frame                
        self.controlFrame = ControlFrame(self)
        self.controlFrame.grid(column = 1, row = 1, columnspan = 2, sticky = (N, W), padx = 10,
                               pady = 55)

        # time frame
        self.timeFrame = TimeFrame(self)
        self.timeFrame.grid(column = 1, row = 2, columnspan = 2, sticky = (N, W), padx = 10)


        self.columnconfigure(0, weight = 1)
        self.rowconfigure(2, weight = 1)


    def orderReport(self, byWhat):
        "orders control report"
        opened = {}
        for child in self.contentTree.get_children():
            opened[child] = self.contentTree.item(child, "open")
            self.contentTree.delete(child)
        self.controlReport.orderedBy = byWhat
        self.controlReport.updateTree()
        for child in self.contentTree.get_children():
            if child in opened:
                self.contentTree.item(child, open=opened[child])


    def refresh(self):
        "refreshes the tree after adding a comment"
        self.controlReport.clear(clearAll = False)
        self.controlReport.updateTree()
        

    def filePopUp(self, event):
        "pop-up menu for file item in the tree"
        menu = Menu(self, tearoff = 0)
        item = self.contentTree.identify("item", event.x, event.y)
        name = item.rstrip("0123456789")
        if name in self.fileStorage.tagged:
            menu.add_command(label = "Remove tag", command = lambda: self.removeTag(name))
        else:
            menu.add_command(label = "Add tag", command = lambda: self.addTag(name))
        menu.add_command(label = "Add comment", command = lambda: Comment(self, name))
        menu.add_separator()
        label = "Open arena file" if m.files == "pair" else "Open file"
        menu.add_command(label = label, command = lambda: self.openFile("arena", name))
        if m.files == "pair":
            menu.add_command(label = "Open room file",
                             command = lambda: self.openFile("room", name))
        menu.post(event.x_root, event.y_root)
        
    def controlPopUp(self, event):
        "pop-up menu for control item in the tree"
        menu = Menu(self, tearoff = 0)
        item = self.contentTree.identify("item", event.x, event.y)
        menu.add_command(label = "Add tags to all problem files",
                         command = lambda: self.addMoreTags(item, specified = ["Problem"]))
        menu.add_command(label = "Add tags to all files with at least a warning",
                         command = lambda: self.addMoreTags(item, specified =
                                                            ["Problem", "Warning"]))
        menu.add_command(label = "Add tags to all files with at least a concern",
                         command = lambda: self.addMoreTags(item, specified =
                                                            ["Problem", "Warning", "Concern"]))
        menu.add_separator()
        menu.add_command(label = "Remove tags from all problem files",
                         command = lambda: self.removeMoreTags(item, specified = ["Problem"]))
        menu.add_command(label = "Remove tags from all files with at least a warning",
                         command = lambda: self.removeMoreTags(item, specified =
                                                               ["Problem", "Warning"]))
        menu.add_command(label = "Remove tags from all files with at least a concern",
                         command = lambda: self.removeMoreTags(item, specified =
                                                               ["Problem", "Warning", "Concern"]))
        menu.post(event.x_root, event.y_root)
        
    def okPopUp(self, event):
        "pop-up menu for rest of files item in the tree"
        menu = Menu(self, tearoff = 0)
        item = self.contentTree.identify("item", event.x, event.y)
        menu.add_command(label = "Add tags to all OK files",
                         command = lambda: self.addMoreTags(item))
        menu.add_command(label = "Remove tags from all OK files",
                         command = lambda: self.removeMoreTags(item))
        menu.post(event.x_root, event.y_root)
        
    def openFile(self, frame, arenafile):
        "opens selected file; called from filePopUp"
        if frame == "room":
            if arenafile in self.fileStorage.pairedfiles:
                roomfile = self.fileStorage.pairedfiles[arenafile]
            else:
                if "Arena" in os.path.basename(arenafile):
                    splitName = os.path.split(arenafile)
                    roomfile = os.path.join(splitName[0], splitName[1].replace("Arena", "Room"))                    
                elif "arena" in os.path.basename(arenafile):
                    splitName = os.path.split(arenafile)
                    roomfile = os.path.join(splitName[0], splitName[1].replace("arena", "room"))
            if roomfile:
                os.startfile(roomfile)
            else:
                self.bell()
        elif frame == "arena":
            os.startfile(arenafile)

    def addTag(self, name):
        "adds tag to a single file"
        for num in range(len(self.controlReport.controls)):
            self.contentTree.set(name + str(num), "tag", "x")
        self.fileStorage.tag(name)
        
    def removeTag(self, name):
        "removes tag from a single file"
        for num in range(len(self.controlReport.controls)):
            self.contentTree.set(name + str(num), "tag", " ")
        self.fileStorage.tagged.remove(name)
        
    def addMoreTags(self, item, specified = False):
        "adds tags to more files; specified used for importance, e.g. ['Problem', 'Warning']"
        num = self.contentTree.index(item)
        for child in self.contentTree.get_children(item):
            name = child.rstrip("0123456789")
            if specified and not self.contentTree.set(name + str(num), "importance") in specified:
                next
            else:
                self.addTag(name)

    def removeMoreTags(self, item, specified = False):
        "removes tags to more files; specified used for importance, e.g. ['Problem', 'Warning']"
        num = self.contentTree.index(item)
        for child in self.contentTree.get_children(item):
            name = child.rstrip("0123456789")
            if specified and not self.contentTree.set(name + str(num), "importance") in specified:
                next
            else:
                if name in self.fileStorage.tagged:
                    self.removeTag(name)    

       
    def treeDoubleClick(self, event):
        "shows tracks in a ShowTracks toplevel window"
        item = self.contentTree.identify("item", event.x, event.y)
        name = item.rstrip("0123456789")
        tracks = self.controlReport.files # <- zmenit aby zobrazovalo serazene
        if item:
            showTracks = ShowTracks(self, nameA = name, tracks = tracks, controlled = True)


    def controlFun(self):
        "processes selected files, clears report, shows results in a report"

        # progressbar
        if len(self.fileStorage) > 1:
            self.stoppedProcessing = False
            self.progressWindow = ProgressWindow(self, len(self.fileStorage),
                                                 text = "controlled")

        # initialization
        controls = self.controlFrame.controlsGet() # selected controls
        self.controlReport.clear()  # clears report
        self.controlReport.addControls(controls) # adds selected controls to ControlReport

        self.problemOccured = False
        # processing      
        for file in self.fileStorage:
            tag = "x" if file in self.fileStorage.tagged else " "
            try:
                if file in self.fileStorage.pairedfiles:
                    cm = m.CL(file, self.fileStorage.pairedfiles[file])
                else:
                    cm = m.CL(file, "auto")
            except Exception:
                self.problemOccured = True
                for control in controls:
                    self.controlReport.addFile((control[0], [file, "Failed to load!", "Problem",
                                                             9999999, tag]))
            else:
                for control in controls:
                    try:
                        assessment = self.assessImportance(cm = cm, control = control, file = file)
                        assessment[1].append(tag)
                    except Exception:
                        self.problemOccured = True
                        assessment = (control[0], [file, "Failed to compute!", "Problem",
                                                   9999998, tag])
                    self.controlReport.addFile(assessment)
                     
            if len(self.fileStorage) > 1:
                if self.stoppedProcessing:
                    return
                else:
                    self.progressWindow.addOne()
                    
        self.controlReport.updateTree()

        # progressbar and status
        if len(self.fileStorage) > 1:
            self.progressWindow.destroy()
            if self.problemOccured:
                self.status.set("Files were not processed successfully!")
                self.bell()
            else:
                self.status.set("Files were processed successfully.")
        else:
            if self.problemOccured:
                self.status.set("File was not processed successfully!")
                self.bell()
            else:
                self.status.set("File was processed successfully.")          
        

    def assessImportance(self, cm, control, file):
        "method needed for evaluation of importance of results from CM class' control methods"
        method = control[0]
        startTime, time = int(self.timeFrame.startTimeVar.get()), int(self.timeFrame.timeVar.get())
        results = eval("cm.{}".format(control[1]))
        description = ""
        importance = ""
        value = 0
        
        if method == "Reflections":
            if results[1] * 3 + results[0] > 5:
                importance = "Problem"
            elif results[1] * 3 + results[0] > 2:
                importance = "Warning"
            elif results[0] > 0:
                importance = "Concern"
            else:
                importance = "OK"
            if results[1] != 1:
                description = "{} points problematic, {} of concern".format(results[1], results[0])
            else:
                description = "{} point problematic, {} of concern".format(results[1], results[0])
            value = results[1]

            self.fileStorage.saveReflections(file = file, points = results[2] + results[3])
            
        elif method == "Outside Points":
            if results > 250:
                importance = "Problem"
            elif results > 50:
                importance = "Warning"
            elif results > 5:
                importance = "Concern"
            else:
                importance = "OK"
            if results != 1:
                description = "{} points outside of arena".format(results)
            else:
                description = "1 point outside of arena"
            value = results

        elif method == "Bad Points":
            results = float(results)
            if results > 10:
                importance = "Problem"
            elif results > 5:
                importance = "Warning"
            elif results > 2:
                importance = "Concern"
            else:
                importance = "OK"
            description = "{0:.2f}% bad points".format(results)
            value = results            
                    
        return (method, [cm.nameA, description, importance, value])

            
    def saveFun(self):
        "writes results from controlReport to selected file"
        output = self.saveToFrame.saveToVar.get()
        if not self.controlReport.files:
            self.bell()
            self.status.set("No results prepared for saving.")
            return
        if not output:
            self.bell()
            self.status.set("You have to select a name of a file.")
            return
        
        separator = optionGet("ResultSeparator", ",", "str", True)
        results = separator.join(["File"] + self.controlReport.controls)
        for file in self.controlReport.files:
            filename = returnName(filename = file, allFiles = self.controlReport.files)
            result = [filename]
            for control in self.controlReport.controls:
                result += [i[3] for i in self.controlReport.results[control] if i[0] == file]
            results += "\n" + separator.join(map(str, result))
     
        writeResults(output, results)
        self.status.set("Results were saved.")
        

    def checkProcessing(self):
        "method updating page after change of notebook tab"
        self.controlReport.clear(clearAll = False)
        self.controlReport.updateTree()
        
        if self.fileStorage.arenafiles:
            self.process.state(["!disabled"])
        else:
            self.process.state(["disabled"])

        if self.fileStorage.arenafiles or self.fileStorage.wrongfiles:
            self.fileStorageFrame.removeFiles.state(["!disabled"])
        else:
            self.fileStorageFrame.removeFiles.state(["disabled"])

        self.fileStorageFrame.chosenVar.set(len(self.fileStorage))
        self.fileStorageFrame.nonMatchingVar.set(len(self.fileStorage.wrongfiles))
コード例 #14
0
    def __init__(self, root):
        super().__init__(root)

        self.root = root
        placeWindow(self, 598, 208)
        self.title = "Set batch time"
        self.grab_set()
        self.focus_set()
        self.resizable(False, False)

        self.batchTime = optionGet("LastBatchTime", "[(0, 20)]", "list")
        self.developer = optionGet("Developer", False, 'bool')
        self.manualChangeEnabled = self.developer

        # frames
        self.buttonFrame = ttk.Frame(self)
        self.removeFrame = ttk.Frame(self)
        self.timeFrame = TimeFrame(self, observe=False)

        # buttons
        self.okBut = ttk.Button(self, text="Ok", command=self.okFun)
        self.closeBut = ttk.Button(self, text="Close", command=self.destroy)
        self.addBut = ttk.Button(self.buttonFrame,
                                 text="Add",
                                 command=self.addFun,
                                 width=8)
        self.removeLastBut = ttk.Button(self.removeFrame,
                                        text="Remove last",
                                        command=self.removeLastFun)
        self.resetBut = ttk.Button(self.removeFrame,
                                   text="Reset",
                                   command=self.resetFun)
        self.clearBut = ttk.Button(self.removeFrame,
                                   text="Clear",
                                   command=self.clearFun)

        # text
        self.text = Text(self, height=5, wrap="word", width=73)
        self.text.insert("1.0", self.batchTime)
        self.text.bind("<3>", lambda e: self.popUp(e))
        if not self.developer:
            self.text["state"] = "disabled"
            self.text["background"] = self._color()
        else:
            self.addBut["state"] = "disabled"
            self.removeLastBut["state"] = "disabled"

        # adding to grid
        self.buttonFrame.grid(column=1, row=0, sticky=W, pady=2)
        self.removeFrame.grid(column=3, row=0, pady=3)
        self.timeFrame.grid(column=0, row=0)

        self.okBut.grid(column=3, row=2, pady=2)
        self.closeBut.grid(column=2, row=2, pady=2)
        self.addBut.grid(column=0, row=2, columnspan=2)
        self.removeLastBut.grid(column=0, row=0, pady=0)
        self.resetBut.grid(column=0, row=1, pady=2)
        self.clearBut.grid(column=0, row=2, pady=0)

        self.text.grid(column=0, row=1, columnspan=4, pady=5, padx=5)

        # +x buttons
        ttk.Button(self.buttonFrame,
                   text="+1",
                   command=lambda: self.addTime(1),
                   width=3).grid(column=0, row=0)
        ttk.Button(self.buttonFrame,
                   text="+2",
                   command=lambda: self.addTime(2),
                   width=3).grid(column=1, row=0)
        ttk.Button(self.buttonFrame,
                   text="+5",
                   command=lambda: self.addTime(5),
                   width=3).grid(column=0, row=1)
        ttk.Button(self.buttonFrame,
                   text="+10",
                   command=lambda: self.addTime(10),
                   width=3).grid(column=1, row=1)
コード例 #15
0
class FileTree(ttk.Frame):
    "displays files in ShowTracks class"

    def __init__(self, root, files, controlled=False):
        super().__init__(root)

        self.rowconfigure(0, weight=1)

        self.allFiles = files  # used when un-selecting files
        self.files = files  # currently diplayed files
        self.controlled = controlled  # True if FileTree called from controller
        self.root = root
        self.fileStorage = self.root.fileStorage
        self.index = self.root.index  # which file is selected when the FileTree is initialized
        self.usedProblemOrder = -1  # by which method is the tree ordered (index)

        # tree
        self.treeFrame = ttk.Frame(self)
        self.treeFrame.grid(column=0, row=0, columnspan=3, sticky=(N, S, E, W))
        self.treeFrame.rowconfigure(0, weight=1)
        self.treeFrame.columnconfigure(0, weight=1)

        self.tree = ttk.Treeview(self.treeFrame,
                                 selectmode="browse",
                                 height=20)
        self.tree.grid(column=0, row=0, sticky=(N, S, E, W))

        if self.controlled:
            columns = ("problem", "tag")
        else:
            columns = ("tag")
        self.tree["columns"] = columns

        self.tree.column("#0", width=240, anchor="w")
        self.tree.heading("#0", text="File", command=self.orderByNames)

        self.tree.column("tag", width=40, anchor="center")
        self.tree.heading("tag", text="Tag", command=self.orderByTag)

        if self.controlled:
            self.tree.column("problem", width=160, anchor="e")
            self.tree.heading("problem",
                              text="Problems",
                              command=self.orderByProblem)

        self.scrollbar = ttk.Scrollbar(self.treeFrame,
                                       orient=VERTICAL,
                                       command=self.tree.yview)
        self.scrollbar.grid(column=1, row=0, sticky=(N, S, E))
        self.tree.configure(yscrollcommand=self.scrollbar.set)

        self.tree.bind("<1>", lambda e: self.click(e))
        self.tree.bind("<3>", lambda e: self.popUp(e))

        self.tree.tag_configure("comment", background=commentColor())

        self.drawTree()

        # bottom frame
        self.bottomFrame = ttk.Frame(self)
        self.bottomFrame.grid(column=0, row=1, columnspan=2)
        self.bottomFrame.columnconfigure(3, weight=1)
        self.bottomFrame.rowconfigure(1, weight=1)

        # previous and next buttons
        self.fileLabFrame = ttk.Labelframe(self.bottomFrame, text="File")
        self.fileLabFrame.grid(column=0, row=0, sticky=(N, W), pady=3, padx=1)

        self.previousBut = ttk.Button(self.fileLabFrame,
                                      text="Previous",
                                      command=self.previousFun)
        self.previousBut.grid(column=0, row=0, padx=3)

        self.nextBut = ttk.Button(self.fileLabFrame,
                                  text="Next",
                                  command=self.nextFun)
        self.nextBut.grid(column=1, row=0, padx=3)

        # tag buttons
        self.tagLabFrame = ttk.Labelframe(self.bottomFrame, text="Tagging")
        self.tagLabFrame.grid(column=0,
                              row=1,
                              sticky=(N, W),
                              rowspan=2,
                              padx=1,
                              pady=4)

        self.tagBut = ttk.Button(self.tagLabFrame,
                                 text="Tag file",
                                 command=self.tagFun)
        self.tagBut.grid(column=1, row=1, padx=3)
        self.checkTag()

        self.tagAllBut = ttk.Button(self.tagLabFrame,
                                    text="Tag all",
                                    command=self.tagAllFun)
        self.tagAllBut.grid(column=2, row=1, padx=3)

        self.untagAllBut = ttk.Button(self.tagLabFrame,
                                      text="Remove all tags",
                                      command=self.untagAllFun)
        self.untagAllBut.grid(column=3, row=1, padx=3)

        # time frame
        self.timeLabFrame = ttk.Labelframe(self.bottomFrame, text="Time")
        self.timeLabFrame.grid(column=3, row=0, rowspan=2, sticky=N, pady=3)
        self.timeLabFrame.root = self.root

        self.timeFrame = TimeFrame(self.timeLabFrame,
                                   onChange=True,
                                   observe=False)
        self.timeFrame.grid(column=0, row=0)
        self.timeFrame.timeVar.set(TimeFrame.stop)
        self.timeFrame.startTimeVar.set(TimeFrame.start)

        # remove reflections checkbutton
        self.removeReflectionsVar = BooleanVar()
        self.removeReflectionsVar.set(False)
        self.removeReflections = ttk.Checkbutton(
            self.bottomFrame,
            text="Remove reflections",
            variable=self.removeReflectionsVar,
            command=self.toggleReflections)
        self.removeReflections.grid(column=2,
                                    row=2,
                                    padx=7,
                                    pady=5,
                                    sticky=(N, W),
                                    columnspan=2)

        # frame radiobuttons
        self.frameFrame = ttk.Labelframe(self.bottomFrame, text="Frame")
        self.frameFrame.grid(column=2,
                             row=0,
                             padx=5,
                             rowspan=2,
                             pady=3,
                             sticky=N)

        self.frameVar = StringVar()
        self.frameVar.set("arena")

        self.arenaFrameRB = ttk.Radiobutton(self.frameFrame,
                                            text="Arena",
                                            variable=self.frameVar,
                                            value="arena",
                                            command=self.toggleFrame)
        self.arenaFrameRB.grid(column=0, row=0, pady=2)

        self.roomFrameRB = ttk.Radiobutton(self.frameFrame,
                                           text="Room",
                                           variable=self.frameVar,
                                           value="room",
                                           command=self.toggleFrame)
        self.roomFrameRB.grid(column=0, row=1, pady=2)

    def toggleFrame(self):
        "called when frame is changed - just refreshes canvases"
        self.root.drawTracks(new=False)

    def toggleReflections(self):
        "called when reflections removal is changed - just refreshes canvases"
        if self.removeReflectionsVar.get():
            self.root.drawTracks(new=False)
        else:
            self.root.drawTracks(new=True)

    def tagAllFun(self):
        "tags all displayed files"
        for file in self.files:
            self.fileStorage.tag(file)
        self.drawTree()
        self.tagBut["text"] = "Remove tag"
        self.tagBut["command"] = self.untagFun

    def untagAllFun(self):
        "untags all displayed files"
        for file in self.files:
            if file in self.fileStorage.tagged:
                self.fileStorage.tagged.remove(file)
        self.drawTree()
        self.tagBut["text"] = "Tag file"
        self.tagBut["command"] = self.tagFun

    def tagFun(self, index="none"):
        "tags the selected file"
        selected = self.files[eval(self.tree.selection()[0])]
        if index != "none":
            self.index = index
        else:
            self.tagBut["text"] = "Remove tag"
            self.tagBut["command"] = self.untagFun
        self.fileStorage.tag(self.files[self.index])
        self.drawTree(selected=selected)

    def untagFun(self, index="none"):
        "untags the selected file"
        selected = self.files[eval(self.tree.selection()[0])]
        if index != "none":
            self.index = index
        else:
            self.tagBut["text"] = "Tag file"
            self.tagBut["command"] = self.tagFun
        self.fileStorage.tagged.remove(self.files[self.index])
        self.drawTree(selected=selected)

    def checkTag(self):
        "checks the state of tag button"
        if self.files[self.index] in self.fileStorage.tagged:
            command = self.untagFun
            text = "Remove tag"
        else:
            command = self.tagFun
            text = "Tag file"
        self.tagBut["text"] = text
        self.tagBut["command"] = command

    def click(self, event):
        "called when item in tree is clicked"
        item = self.tree.identify("item", event.x, event.y)
        if item:
            self.tree.selection_set(item)
            self.index = int(item)
            self.root.drawTracks(new=True)
            self.checkTag()

    def previousFun(self):
        "shows previous file"
        if self.index != 0:
            self.prevIndex = self.index
            self.index -= 1
            self.root.drawTracks(new=True)
            self.tree.selection_set(str(self.index))
            self.tree.see(str(self.index))
            self.checkTag()

    def nextFun(self):
        "shows next file"
        if self.index != len(self.files) - 1:
            self.prevIndex = self.index
            self.index += 1
            self.root.drawTracks(new=True)
            self.tree.selection_set(str(self.index))
            self.tree.see(str(self.index))
            self.checkTag()

    def orderByNames(self):
        "orders files by names"
        selected = self.files[eval(self.tree.selection()[0])]
        self.files.sort()
        self.drawTree(selected=selected)

    def orderByTag(self):
        "order files by tags"
        selected = self.files[eval(self.tree.selection()[0])]
        self.files.sort(key=lambda i: (i in self.fileStorage.tagged),
                        reverse=True)
        self.drawTree(selected=selected)

    def orderByProblem(self):
        """orders files by problem - which is displayed (the problem by which files are ordered
            changes when the function is used again)"""
        selected = self.files[eval(self.tree.selection()[0])]
        self.usedProblemOrder = (self.usedProblemOrder + 1) % \
                                len(self.root.root.controlReport.controls)
        method = self.root.root.controlReport.controls[self.usedProblemOrder]
        results = self.root.root.controlReport.results[method]
        values = {tup[0]: tup[3] for tup in results}
        self.tree.heading("problem", text=("Problems (by {})".format(method)))

        self.files.sort(key=lambda i: values[i], reverse=True)
        self.drawTree(selected=selected)

    def drawTree(self, selected=None):
        "initializes (or refreshes) tree"
        for child in self.tree.get_children():
            self.tree.delete(child)

        for count, file in enumerate(self.files):
            tag = "x" if file in self.fileStorage.tagged else ""

            if self.controlled:
                problemKey = {
                    "Problem": "P",
                    "Warning": "W",
                    "Concern": "C",
                    "OK": "O"
                }
                methodKey = {
                    "Reflections": "Ref",
                    "Bad Points": "BP",
                    "Outside Points": "OP"
                }
                problem = ""
                for method in self.root.root.controlReport.results:
                    importance = [i[2] for i in self.root.root.controlReport.results[method] if\
                                  i[0] == file]
                    problem = problem + methodKey[method] + ": " + problemKey[
                        importance[0]] + ", "
                problem = problem[:-2]
                values = (problem, tag)
            else:
                values = (tag)

            comment = "comment" if self.fileStorage.comments[
                file] else "withoutComment"
            self.tree.insert("",
                             "end",
                             str(count),
                             text=returnName(file, self.files),
                             values=values,
                             tag=comment)

        if selected:
            self.index = self.files.index(selected)

        if self.files:
            self.tree.selection_set(str(self.index))
            self.tree.see(str(self.index))

    def refresh(self):
        "refreshes the tree after adding a comment"
        selected = self.files[eval(self.tree.selection()[0])]
        self.drawTree(selected=selected)

    def popUp(self, event):
        "called when tree item is clicked on"
        item = self.tree.identify("item", event.x, event.y)
        menu = Menu(self, tearoff=0)
        if item:
            file = self.files[int(item)]
            menu.add_command(label="Add comment",
                             command=lambda: Comment(self, file))
            if file in self.fileStorage.tagged:
                menu.add_command(
                    label="Remove tag",
                    command=lambda: self.untagFun(index=int(item)))
            else:
                menu.add_command(label="Add tag",
                                 command=lambda: self.tagFun(index=int(item)))
        elif self.controlled:
            menu.add_command(label='Leave only Bad Points',
                             command=lambda: self.leaveOnlyFun("Bad Points"))
            menu.add_command(label='Leave only Reflections',
                             command=lambda: self.leaveOnlyFun("Reflections"))
            menu.add_command(
                label='Leave only Outside Points',
                command=lambda: self.leaveOnlyFun("Outside Points"))
            menu.add_separator()
            menu.add_command(label="Return all",
                             command=lambda: self.leaveOnlyFun("all"))
        menu.post(event.x_root, event.y_root)

    def leaveOnlyFun(self, problem):
        "leaves only files with some problem; or show all files again if problem == 'all'"
        if self.files:
            currentFile = self.files[self.index]
        else:
            currentFile = None

        if problem != "all":
            self.files = [
                file for file in self.files if file in [
                    i[0] for i in self.root.root.controlReport.results[problem]
                    if i[2] != "OK"
                ]
            ]
        else:
            self.files = self.allFiles

        if currentFile in self.files:
            self.index = self.files.index(currentFile)
        else:
            self.index = 0

        self.drawTree()

        if self.files:
            self.root.drawTracks()
            self.tree.selection_set(str(self.index))
            self.checkTag()
コード例 #16
0
class SetBatchTime(Toplevel):
    "toplevel window where time is chosen for batch processing of files with different times"

    def __init__(self, root):
        super().__init__(root)

        self.root = root
        placeWindow(self, 598, 208)
        self.title = "Set batch time"
        self.grab_set()
        self.focus_set()
        self.resizable(False, False)

        self.batchTime = optionGet("LastBatchTime", "[(0, 20)]", "list")
        self.developer = optionGet("Developer", False, 'bool')
        self.manualChangeEnabled = self.developer

        # frames
        self.buttonFrame = ttk.Frame(self)
        self.removeFrame = ttk.Frame(self)
        self.timeFrame = TimeFrame(self, observe=False)

        # buttons
        self.okBut = ttk.Button(self, text="Ok", command=self.okFun)
        self.closeBut = ttk.Button(self, text="Close", command=self.destroy)
        self.addBut = ttk.Button(self.buttonFrame,
                                 text="Add",
                                 command=self.addFun,
                                 width=8)
        self.removeLastBut = ttk.Button(self.removeFrame,
                                        text="Remove last",
                                        command=self.removeLastFun)
        self.resetBut = ttk.Button(self.removeFrame,
                                   text="Reset",
                                   command=self.resetFun)
        self.clearBut = ttk.Button(self.removeFrame,
                                   text="Clear",
                                   command=self.clearFun)

        # text
        self.text = Text(self, height=5, wrap="word", width=73)
        self.text.insert("1.0", self.batchTime)
        self.text.bind("<3>", lambda e: self.popUp(e))
        if not self.developer:
            self.text["state"] = "disabled"
            self.text["background"] = self._color()
        else:
            self.addBut["state"] = "disabled"
            self.removeLastBut["state"] = "disabled"

        # adding to grid
        self.buttonFrame.grid(column=1, row=0, sticky=W, pady=2)
        self.removeFrame.grid(column=3, row=0, pady=3)
        self.timeFrame.grid(column=0, row=0)

        self.okBut.grid(column=3, row=2, pady=2)
        self.closeBut.grid(column=2, row=2, pady=2)
        self.addBut.grid(column=0, row=2, columnspan=2)
        self.removeLastBut.grid(column=0, row=0, pady=0)
        self.resetBut.grid(column=0, row=1, pady=2)
        self.clearBut.grid(column=0, row=2, pady=0)

        self.text.grid(column=0, row=1, columnspan=4, pady=5, padx=5)

        # +x buttons
        ttk.Button(self.buttonFrame,
                   text="+1",
                   command=lambda: self.addTime(1),
                   width=3).grid(column=0, row=0)
        ttk.Button(self.buttonFrame,
                   text="+2",
                   command=lambda: self.addTime(2),
                   width=3).grid(column=1, row=0)
        ttk.Button(self.buttonFrame,
                   text="+5",
                   command=lambda: self.addTime(5),
                   width=3).grid(column=0, row=1)
        ttk.Button(self.buttonFrame,
                   text="+10",
                   command=lambda: self.addTime(10),
                   width=3).grid(column=1, row=1)

    def _color(self):
        return "grey94"

    def okFun(self):
        "closes the window and saves the selected batch time to root's batch time"
        if not self._checkText():
            return
        self.root.selectedBatchTime = self.batchTime
        optionWrite("LastBatchTime", self.batchTime)
        self.destroy()

    def addFun(self):
        "adds selected time to the text widget as well as to the selected batch time"
        start = int(self.timeFrame.startTimeVar.get())
        end = int(self.timeFrame.timeVar.get())
        newTime = (start, end)
        self.batchTime.append(newTime)
        self._updateText()

    def _updateText(self):
        "updates the text widget"
        state = self.text["state"]
        self.text["state"] = "normal"
        self.text.delete("1.0", "end")
        self.text.insert("1.0", self.batchTime)
        self.text["state"] = state

    def removeLastFun(self):
        "removes the last added time"
        if self.batchTime:
            self.batchTime.pop()
        self._updateText()

    def resetFun(self):
        "resets the text to last batch time used (obtained from options)"
        self.batchTime = optionGet("LastBatchTime", "[(0, 20)]", "list")
        self._updateText()

    def clearFun(self):
        "clears the text"
        self.batchTime = []
        self._updateText()

    def popUp(self, event):
        "pop-up menu for text widget"
        menu = Menu(self, tearoff=0)
        if self.manualChangeEnabled:
            menu.add_command(label="Disable manual change",
                             command=self.disableManualChange)
        else:
            menu.add_command(label="Enable manual change",
                             command=self.enableManualChange)
        menu.post(event.x_root, event.y_root)

    def enableManualChange(self):
        "enables manual text changes"
        self.manualChangeEnabled = True
        self.text["state"] = "normal"
        self.text["background"] = "white"
        self.addBut["state"] = "disabled"
        self.removeLastBut["state"] = "disabled"

    def _checkText(self):
        "checks whether the text is in right format"
        try:
            self.batchTime = eval(self.text.get('1.0', 'end'))
            if not isinstance(self.batchTime, list):
                raise Exception("Selected time must be a list.")
            for pair in self.batchTime:
                if not isinstance(pair, tuple):
                    raise Exception("{} is not a tuple.".format(pair))
                if len(pair) != 2:
                    raise Exception(
                        "{} has more than two items (needs exactly two).".
                        format(pair))
                if not isinstance(pair[0], int):
                    raise Exception("{} is not an integer.".format(pair[0]))
                if not isinstance(pair[1], int):
                    raise Exception("{} is not an integer.".format(pair[1]))
                if pair[0] >= pair[1]:
                    raise Exception(
                        "The first item in every pair must be lower than the second."
                    )
        except Exception as e:
            messagebox.showinfo(
                message="There is an error in the selected batch time.\n"
                "Correct it or use Reset or Clear buttons.",
                detail=e,
                title="Error in selected time",
                icon="error")
            return False
        else:
            return True

    def disableManualChange(self):
        "disables manual text changes"
        if not self._checkText():
            return
        self.manualChangeEnabled = False
        self.text["state"] = "disabled"
        self.text["background"] = self._color()
        self.addBut["state"] = "normal"
        self.removeLastBut["state"] = "normal"

    def addTime(self, x):
        "adds time to start and stop time in timeFrame"
        start = int(self.timeFrame.startTimeVar.get()) + x
        end = int(self.timeFrame.timeVar.get()) + x
        self.timeFrame.startTimeVar.set(str(start))
        self.timeFrame.timeVar.set(str(end))
コード例 #17
0
ファイル: explorer.py プロジェクト: bahniks/CM_Manager_0_3_4
    def __init__(self, root):
        super().__init__(root)
        
        self["padding"] = (10, 10, 12, 12)

        self.animate = "stop"
        self.initialized = False
        self.root = root
        self.fileStorage = self.root.fileStorage

        # variables
        self.status = StringVar()
        self.curTime = DoubleVar()
        self.speed = DoubleVar()
        self.graphTypeVar = StringVar()
        self.distanceVar = StringVar()
        self.entrancesVar = StringVar()
        self.timeVar = StringVar()
        self.totDistanceVar = StringVar()
        self.totEntrancesVar = StringVar()
        self.showTrackVar = BooleanVar()
        self.removeReflectionsVar = BooleanVar()
        self.showShocksVar = BooleanVar()
        self.saveWhatVar = StringVar()
        self.saveWhichFilesVar = StringVar()

        self.curTime.set(0)
        self.speed.set(1.0)
        self.graphTypeVar.set("SpeedGraph(self)")
        self.showTrackVar.set(False)
        self.removeReflectionsVar.set(False)
        self.showShocksVar.set(True)
        self.saveWhatVar.set("both frames")
        self.saveWhichFilesVar.set("current")
        
        
        # frames
        self.controlsLF = ttk.Labelframe(self, text = "Controls")
        self.graphLF = ttk.Labelframe(self, text = "Graph")
        self.fileStorageFrame = FileStorageFrame(self, parent = "explorer")
        self.fileFrame = FileFrame(self)
        self.parametersLF = ttk.LabelFrame(self, text = "Parameters")
        self.timeLabFrame = ttk.Labelframe(self, text = "Time")
        self.timeLabFrame.root = self
        self.timeFrame = TimeFrame(self.timeLabFrame, onChange = True)
        self.arenaFrame = ttk.LabelFrame(self, text = "Arena frame")
        self.roomFrame = ttk.LabelFrame(self, text = "Room frame")
        self.speedScaleFrame = ttk.Frame(self)
        self.speedScaleFrame.rowconfigure(0, weight = 1)
        self.optionsLF = ttk.LabelFrame(self, text = "Options")
        self.saveImagesLF = ttk.LabelFrame(self, text = "Save image(s)")
        
        # canvases
        self.arenaCanv = Canvas(self.arenaFrame, background = "white", height = 300, width = 300)
        self.roomCanv = Canvas(self.roomFrame, background = "white", height = 300, width = 300)

        # buttons
        self.playBut = ttk.Button(self.controlsLF, text = "Play", command = self.playFun,
                                  state = "disabled")
        self.pauseBut = ttk.Button(self.controlsLF, text = "Pause", command = self.pauseFun,
                                   state = "disabled")
        self.stopBut = ttk.Button(self.controlsLF, text = "Stop", command = self.stopFun,
                                  state = "disabled")
        self.saveBut = ttk.Button(self.saveImagesLF, text = "Save", command = self.saveImages,
                                  state = "disabled")

        # checkbuttons
        self.removeReflections = ttk.Checkbutton(self.optionsLF, text = "Remove reflections",
                                                 variable = self.removeReflectionsVar,
                                                 command = self.toggleReflections)
        self.showShocks = ttk.Checkbutton(self.optionsLF, text = "Show shocks",
                                          variable = self.showShocksVar,
                                          command = self.toggleShocks)

        # radiobutton
        self.showTrack = ttk.Radiobutton(self.optionsLF, text = "Show track",
                                         variable = self.showTrackVar, value = True,
                                         command = self.toggleAnimation)
        self.showAnimation = ttk.Radiobutton(self.optionsLF, text = "Show animation",
                                             variable = self.showTrackVar, value = False,
                                             command = self.toggleAnimation)
        
        
        # label
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.distance = ttk.Label(self.parametersLF, textvariable = self.distanceVar, width = 10,
                                  anchor = "e")
        self.entrances = ttk.Label(self.parametersLF, textvariable = self.entrancesVar, width = 10,
                                   anchor = "e")
        self.timePar = ttk.Label(self.parametersLF, textvariable = self.timeVar, width = 10,
                                 anchor = "e")
        self.totDistance = ttk.Label(self.parametersLF, textvariable = self.totDistanceVar,
                                     width = 10, anchor = "e")
        self.totEntrances = ttk.Label(self.parametersLF, textvariable = self.totEntrancesVar,
                                     width = 10, anchor = "e")
        self.distanceLab = ttk.Label(self.parametersLF, text = "Distance [m]", width = 11,
                                     anchor = "w")
        self.entrancesLab = ttk.Label(self.parametersLF, text = "Entrances", width = 11,
                                      anchor = "w")
        self.timeLab = ttk.Label(self.parametersLF, text = "Time", width = 11, anchor = "w")
        self.currentLab = ttk.Label(self.parametersLF, text = "Current", width = 10,
                                    anchor = "e")
        self.totalLab = ttk.Label(self.parametersLF, text = "Total", width = 10,
                                  anchor = "e")
        self.saveWhatLab = ttk.Label(self.saveImagesLF, text = "Save")
        self.saveWhichFilesLab = ttk.Label(self.saveImagesLF, text = "File(s)")

        # scales
        self.timeSc = ttk.Scale(self, orient = HORIZONTAL, from_ = 0, to = 100,
                                variable = self.curTime, command = self.changedTime)
        self.speedSc = ttk.Scale(self.speedScaleFrame, orient = VERTICAL, from_ = 50, to = 0.5,
                                 variable = self.speed, command = self.changedSpeed)
        
        # entry
        self.speedEntry = ttk.Entry(self.speedScaleFrame, textvariable = self.speed, width = 4,
                                    justify = "right", state = "readonly")
        
        # graph
        self.graph = eval(self.graphTypeVar.get())
        self.graph.bind("<Button-1>", self.graphClick)
        self.graph.bind("<Button-3>", self.graphPopUp)

        # combobox
        self.saveWhatCombo = ttk.Combobox(self.saveImagesLF, textvariable = self.saveWhatVar,
                                          justify = "center", width = 15, state = "readonly")
        self.saveWhatCombo["values"] = ("arena frame", "room frame", "both frames",
                                        "graph", "all")
        self.saveWhichFilesCombo = ttk.Combobox(self.saveImagesLF, textvariable =
                                                self.saveWhichFilesVar, justify = "center",
                                                width = 15, state = "readonly")
        self.saveWhichFilesCombo["values"] = ("current", "tagged", "untagged", "all")

        # adding to grid        
        self.controlsLF.grid(column = 0, row = 3, columnspan = 2, sticky = (N, W), pady = 2,
                             padx = 2)
        self.graphLF.grid(column = 0, row = 5, columnspan = 1, pady = 2, padx = 2, sticky = (N, W))
        self.fileStorageFrame.grid(column = 8, row = 0, pady = 2, padx = 3, sticky = (N, W))
        self.fileFrame.grid(column = 8, row = 1, rowspan = 4, padx = 3, sticky = (N, S))
        self.parametersLF.grid(column = 3, row = 3, columnspan = 3)
        self.timeLabFrame.grid(column = 2, row = 5, columnspan = 3, sticky = (W, N), pady = 2)        
        self.timeFrame.grid(column = 0, row = 0)
        self.arenaFrame.grid(column = 0, row = 0, rowspan = 2, columnspan = 3,
                             sticky = (N, S, E, W), padx = 2, pady = 2)
        self.roomFrame.grid(column = 3, row = 0, rowspan = 2, columnspan = 4,
                            sticky = (N, S, E, W), padx = 2, pady = 2)
        self.speedScaleFrame.grid(column = 7, row = 0, rowspan = 2, sticky = (N, S), padx = 4,
                                  pady = 2)
        self.optionsLF.grid(column = 5, row = 5, columnspan = 2, sticky = (N, W), pady = 2)
        self.saveImagesLF.grid(column = 8, row = 5, sticky = (S), pady = 5)
        
        self.arenaCanv.grid(column = 0, row = 0, padx = 1, pady = 1)
        self.roomCanv.grid(column = 0, row = 0, padx = 1, pady = 1)
        self.graph.grid(column = 0, row = 4, columnspan = 7, padx = 2, pady = 5, sticky = (E, W))
        
        self.playBut.grid(column = 0, row = 0, sticky = (N, S), padx = 2, pady = 2)
        self.pauseBut.grid(column = 1, row = 0, sticky = (N, S), padx = 2, pady = 2)
        self.stopBut.grid(column = 2, row = 0, sticky = (N, S), padx = 2, pady = 2)
        self.saveBut.grid(column = 1, row = 2, sticky = E)

        self.removeReflections.grid(column = 0, row = 2, padx = 2, pady = 2, sticky = (N, W))
        self.showShocks.grid(column = 0, row = 3, padx = 2, pady = 2, sticky = (N, W))

        self.showAnimation.grid(column = 0, row = 0, padx = 2, pady = 1, sticky = (N, W))
        self.showTrack.grid(column = 0, row = 1, padx = 2, pady = 1, sticky = (N, W))
        
        self.speedEntry.grid(column = 0, row = 1)

        self.statusBar.grid(column = 0, row = 6, columnspan = 7, sticky = (S, E, W), padx = 2,
                       pady = 2)
        self.distance.grid(column = 1, row = 1, sticky = E)
        self.entrances.grid(column = 1, row = 2, sticky = E)
        self.timePar.grid(column = 1, row = 3, sticky = E)
        self.totDistance.grid(column = 2, row = 1, sticky = E, padx = 4)
        self.totEntrances.grid(column = 2, row = 2, sticky = E, padx = 4)
        self.distanceLab.grid(column = 0, row = 1, sticky = E)
        self.entrancesLab.grid(column = 0, row = 2, sticky = E)
        self.timeLab.grid(column = 0, row = 3, sticky = E)
        self.currentLab.grid(column = 1, row = 0, sticky = E, padx = 2, pady = 2)
        self.totalLab.grid(column = 2, row = 0, sticky = E, padx = 4, pady = 2)
        self.saveWhatLab.grid(column = 0, row = 0, padx = 2, sticky = E)
        self.saveWhichFilesLab.grid(column = 0, row = 1, padx = 2, sticky = E)

        self.timeSc.grid(column = 0, row = 2, columnspan = 7, sticky = (E, W), pady = 4, padx = 2)
        self.speedSc.grid(column = 0, row = 0, sticky = (N, S, E, W), pady = 3)

        self.saveWhatCombo.grid(column = 1, row = 0)
        self.saveWhichFilesCombo.grid(column = 1, row = 1)


        # checkbuttons for graph
        for number, gType in enumerate(getGraphTypes()):
            ttk.Radiobutton(self.graphLF, text = gType[0], variable = self.graphTypeVar,
                            command = self.changedGraph, value = gType[1])\
                            .grid(row = number, pady = 2, padx = 1, sticky = (W))
コード例 #18
0
ファイル: explorer.py プロジェクト: bahniks/CM_Manager_0_3_4
class Explorer(ttk.Frame):
    "represents ''Explore' page in the main window notebook"
    def __init__(self, root):
        super().__init__(root)
        
        self["padding"] = (10, 10, 12, 12)

        self.animate = "stop"
        self.initialized = False
        self.root = root
        self.fileStorage = self.root.fileStorage

        # variables
        self.status = StringVar()
        self.curTime = DoubleVar()
        self.speed = DoubleVar()
        self.graphTypeVar = StringVar()
        self.distanceVar = StringVar()
        self.entrancesVar = StringVar()
        self.timeVar = StringVar()
        self.totDistanceVar = StringVar()
        self.totEntrancesVar = StringVar()
        self.showTrackVar = BooleanVar()
        self.removeReflectionsVar = BooleanVar()
        self.showShocksVar = BooleanVar()
        self.saveWhatVar = StringVar()
        self.saveWhichFilesVar = StringVar()

        self.curTime.set(0)
        self.speed.set(1.0)
        self.graphTypeVar.set("SpeedGraph(self)")
        self.showTrackVar.set(False)
        self.removeReflectionsVar.set(False)
        self.showShocksVar.set(True)
        self.saveWhatVar.set("both frames")
        self.saveWhichFilesVar.set("current")
        
        
        # frames
        self.controlsLF = ttk.Labelframe(self, text = "Controls")
        self.graphLF = ttk.Labelframe(self, text = "Graph")
        self.fileStorageFrame = FileStorageFrame(self, parent = "explorer")
        self.fileFrame = FileFrame(self)
        self.parametersLF = ttk.LabelFrame(self, text = "Parameters")
        self.timeLabFrame = ttk.Labelframe(self, text = "Time")
        self.timeLabFrame.root = self
        self.timeFrame = TimeFrame(self.timeLabFrame, onChange = True)
        self.arenaFrame = ttk.LabelFrame(self, text = "Arena frame")
        self.roomFrame = ttk.LabelFrame(self, text = "Room frame")
        self.speedScaleFrame = ttk.Frame(self)
        self.speedScaleFrame.rowconfigure(0, weight = 1)
        self.optionsLF = ttk.LabelFrame(self, text = "Options")
        self.saveImagesLF = ttk.LabelFrame(self, text = "Save image(s)")
        
        # canvases
        self.arenaCanv = Canvas(self.arenaFrame, background = "white", height = 300, width = 300)
        self.roomCanv = Canvas(self.roomFrame, background = "white", height = 300, width = 300)

        # buttons
        self.playBut = ttk.Button(self.controlsLF, text = "Play", command = self.playFun,
                                  state = "disabled")
        self.pauseBut = ttk.Button(self.controlsLF, text = "Pause", command = self.pauseFun,
                                   state = "disabled")
        self.stopBut = ttk.Button(self.controlsLF, text = "Stop", command = self.stopFun,
                                  state = "disabled")
        self.saveBut = ttk.Button(self.saveImagesLF, text = "Save", command = self.saveImages,
                                  state = "disabled")

        # checkbuttons
        self.removeReflections = ttk.Checkbutton(self.optionsLF, text = "Remove reflections",
                                                 variable = self.removeReflectionsVar,
                                                 command = self.toggleReflections)
        self.showShocks = ttk.Checkbutton(self.optionsLF, text = "Show shocks",
                                          variable = self.showShocksVar,
                                          command = self.toggleShocks)

        # radiobutton
        self.showTrack = ttk.Radiobutton(self.optionsLF, text = "Show track",
                                         variable = self.showTrackVar, value = True,
                                         command = self.toggleAnimation)
        self.showAnimation = ttk.Radiobutton(self.optionsLF, text = "Show animation",
                                             variable = self.showTrackVar, value = False,
                                             command = self.toggleAnimation)
        
        
        # label
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.distance = ttk.Label(self.parametersLF, textvariable = self.distanceVar, width = 10,
                                  anchor = "e")
        self.entrances = ttk.Label(self.parametersLF, textvariable = self.entrancesVar, width = 10,
                                   anchor = "e")
        self.timePar = ttk.Label(self.parametersLF, textvariable = self.timeVar, width = 10,
                                 anchor = "e")
        self.totDistance = ttk.Label(self.parametersLF, textvariable = self.totDistanceVar,
                                     width = 10, anchor = "e")
        self.totEntrances = ttk.Label(self.parametersLF, textvariable = self.totEntrancesVar,
                                     width = 10, anchor = "e")
        self.distanceLab = ttk.Label(self.parametersLF, text = "Distance [m]", width = 11,
                                     anchor = "w")
        self.entrancesLab = ttk.Label(self.parametersLF, text = "Entrances", width = 11,
                                      anchor = "w")
        self.timeLab = ttk.Label(self.parametersLF, text = "Time", width = 11, anchor = "w")
        self.currentLab = ttk.Label(self.parametersLF, text = "Current", width = 10,
                                    anchor = "e")
        self.totalLab = ttk.Label(self.parametersLF, text = "Total", width = 10,
                                  anchor = "e")
        self.saveWhatLab = ttk.Label(self.saveImagesLF, text = "Save")
        self.saveWhichFilesLab = ttk.Label(self.saveImagesLF, text = "File(s)")

        # scales
        self.timeSc = ttk.Scale(self, orient = HORIZONTAL, from_ = 0, to = 100,
                                variable = self.curTime, command = self.changedTime)
        self.speedSc = ttk.Scale(self.speedScaleFrame, orient = VERTICAL, from_ = 50, to = 0.5,
                                 variable = self.speed, command = self.changedSpeed)
        
        # entry
        self.speedEntry = ttk.Entry(self.speedScaleFrame, textvariable = self.speed, width = 4,
                                    justify = "right", state = "readonly")
        
        # graph
        self.graph = eval(self.graphTypeVar.get())
        self.graph.bind("<Button-1>", self.graphClick)
        self.graph.bind("<Button-3>", self.graphPopUp)

        # combobox
        self.saveWhatCombo = ttk.Combobox(self.saveImagesLF, textvariable = self.saveWhatVar,
                                          justify = "center", width = 15, state = "readonly")
        self.saveWhatCombo["values"] = ("arena frame", "room frame", "both frames",
                                        "graph", "all")
        self.saveWhichFilesCombo = ttk.Combobox(self.saveImagesLF, textvariable =
                                                self.saveWhichFilesVar, justify = "center",
                                                width = 15, state = "readonly")
        self.saveWhichFilesCombo["values"] = ("current", "tagged", "untagged", "all")

        # adding to grid        
        self.controlsLF.grid(column = 0, row = 3, columnspan = 2, sticky = (N, W), pady = 2,
                             padx = 2)
        self.graphLF.grid(column = 0, row = 5, columnspan = 1, pady = 2, padx = 2, sticky = (N, W))
        self.fileStorageFrame.grid(column = 8, row = 0, pady = 2, padx = 3, sticky = (N, W))
        self.fileFrame.grid(column = 8, row = 1, rowspan = 4, padx = 3, sticky = (N, S))
        self.parametersLF.grid(column = 3, row = 3, columnspan = 3)
        self.timeLabFrame.grid(column = 2, row = 5, columnspan = 3, sticky = (W, N), pady = 2)        
        self.timeFrame.grid(column = 0, row = 0)
        self.arenaFrame.grid(column = 0, row = 0, rowspan = 2, columnspan = 3,
                             sticky = (N, S, E, W), padx = 2, pady = 2)
        self.roomFrame.grid(column = 3, row = 0, rowspan = 2, columnspan = 4,
                            sticky = (N, S, E, W), padx = 2, pady = 2)
        self.speedScaleFrame.grid(column = 7, row = 0, rowspan = 2, sticky = (N, S), padx = 4,
                                  pady = 2)
        self.optionsLF.grid(column = 5, row = 5, columnspan = 2, sticky = (N, W), pady = 2)
        self.saveImagesLF.grid(column = 8, row = 5, sticky = (S), pady = 5)
        
        self.arenaCanv.grid(column = 0, row = 0, padx = 1, pady = 1)
        self.roomCanv.grid(column = 0, row = 0, padx = 1, pady = 1)
        self.graph.grid(column = 0, row = 4, columnspan = 7, padx = 2, pady = 5, sticky = (E, W))
        
        self.playBut.grid(column = 0, row = 0, sticky = (N, S), padx = 2, pady = 2)
        self.pauseBut.grid(column = 1, row = 0, sticky = (N, S), padx = 2, pady = 2)
        self.stopBut.grid(column = 2, row = 0, sticky = (N, S), padx = 2, pady = 2)
        self.saveBut.grid(column = 1, row = 2, sticky = E)

        self.removeReflections.grid(column = 0, row = 2, padx = 2, pady = 2, sticky = (N, W))
        self.showShocks.grid(column = 0, row = 3, padx = 2, pady = 2, sticky = (N, W))

        self.showAnimation.grid(column = 0, row = 0, padx = 2, pady = 1, sticky = (N, W))
        self.showTrack.grid(column = 0, row = 1, padx = 2, pady = 1, sticky = (N, W))
        
        self.speedEntry.grid(column = 0, row = 1)

        self.statusBar.grid(column = 0, row = 6, columnspan = 7, sticky = (S, E, W), padx = 2,
                       pady = 2)
        self.distance.grid(column = 1, row = 1, sticky = E)
        self.entrances.grid(column = 1, row = 2, sticky = E)
        self.timePar.grid(column = 1, row = 3, sticky = E)
        self.totDistance.grid(column = 2, row = 1, sticky = E, padx = 4)
        self.totEntrances.grid(column = 2, row = 2, sticky = E, padx = 4)
        self.distanceLab.grid(column = 0, row = 1, sticky = E)
        self.entrancesLab.grid(column = 0, row = 2, sticky = E)
        self.timeLab.grid(column = 0, row = 3, sticky = E)
        self.currentLab.grid(column = 1, row = 0, sticky = E, padx = 2, pady = 2)
        self.totalLab.grid(column = 2, row = 0, sticky = E, padx = 4, pady = 2)
        self.saveWhatLab.grid(column = 0, row = 0, padx = 2, sticky = E)
        self.saveWhichFilesLab.grid(column = 0, row = 1, padx = 2, sticky = E)

        self.timeSc.grid(column = 0, row = 2, columnspan = 7, sticky = (E, W), pady = 4, padx = 2)
        self.speedSc.grid(column = 0, row = 0, sticky = (N, S, E, W), pady = 3)

        self.saveWhatCombo.grid(column = 1, row = 0)
        self.saveWhichFilesCombo.grid(column = 1, row = 1)


        # checkbuttons for graph
        for number, gType in enumerate(getGraphTypes()):
            ttk.Radiobutton(self.graphLF, text = gType[0], variable = self.graphTypeVar,
                            command = self.changedGraph, value = gType[1])\
                            .grid(row = number, pady = 2, padx = 1, sticky = (W))


    def saveImages(self):
        "saves images for selected files"
        files = self._returnSelectedFiles()

        if len(files) > 1:
            progress = ProgressWindow(self, len(files), text = "saved")
        elif len(files) == 1:
            self.root.config(cursor = "wait")
            self.root.update()
        elif len(files) == 0:
            self.status.set("No file selected.")
            self.bell()
            return

        problems = 0
        for filename in files:
            try:
                if filename in self.fileStorage.pairedfiles:
                    cm = CM(filename, nameR = self.fileStorage.pairedfiles[filename])
                else:
                    cm = CM(filename, nameR = "auto")
                if self.removeReflectionsVar.get():
                    cm.removeReflections(points = self.fileStorage.reflections.get(filename, None))
                self.saveOneImage(cm, filename)               
            except Exception:
                problems += 0

            if len(files) > 1:
                progress.addOne()

        if len(files) > 1:
            progress.destroy()
            if problems > 1:
                self.status.set("{} problems occured!".format(problems))
                self.bell()
            elif problems == 1:
                self.status.set("One problem occured!")
                self.bell()
            else:
                self.status.set("Images were saved.")
        else:
            if problems:
                self.status.set("A problem occured!")
                self.bell()
            else:
                self.status.set("Image was saved.")
            self.root.config(cursor = "")


    def saveOneImage(self, cm, filename):
        "saves image for one file"
        directory = optionGet("ImageDirectory", os.getcwd(), "str")
        # pridat moznost scale u vsech SVG
        
        what =  self.saveWhatVar.get()    

        if what == "both frames":
            self.svg = SVG(600, 300)
            self.saveArenaFrame(cm)
            self.saveRoomFrame(cm, origin = (300, 0))
        elif what == "arena frame":
            self.svg = SVG(300, 300) 
            self.saveArenaFrame(cm)
        elif what == "room frame":
            self.svg = SVG(300, 300)
            self.saveRoomFrame(cm)
        elif what == "graph":
            self.svg = SVG(600, 120)
            self.saveGraph(cm)
        elif what == "all":
            self.svg = SVG(600, 420)
            self.saveArenaFrame(cm)
            self.saveRoomFrame(cm, origin = (300, 0))
            self.saveGraph(cm, origin = (0, 300))
            
        self.svg.save(os.path.join(directory, os.path.splitext(os.path.basename(filename))[0] +
                                   "_" + what.replace(" ", "_") + ".svg")) # upravit
            

    def saveArenaFrame(self, cm, origin = (0, 0)):
        "saves info about arena frame in self.svg"
        self.svg.drawAAPA(cm, frame = "arena", startTime = int(self.timeFrame.startTimeVar.get()),
                         time = int(self.timeFrame.timeVar.get()), boundary = True,
                         sector = False, shocks = False, origin = origin) # dat do options


    def saveRoomFrame(self, cm, origin = (0, 0)):
        "saves info about room frame in self.svg"
        self.svg.drawAAPA(cm, frame = "room", startTime = int(self.timeFrame.startTimeVar.get()),
                         time = int(self.timeFrame.timeVar.get()), boundary = True,
                         sector = True, shocks = True, origin = origin)


    def saveGraph(self, cm, origin = (0, 0)):
        "saves info about graph in self.svg"
        size = (600, 120)
        graph = eval(self.graphTypeVar.get()[:-1] + ', cm, purpose = "svg")')
        yCoordinates, maxY, furtherText = graph.saveGraph(cm)
        points = []
        if yCoordinates:
            length = len(yCoordinates) - 1
            for count, y in enumerate(yCoordinates):       
                points.append(((count * size[0]) / length, size[1] - ((y * size[1]) / maxY)))
        self.svg.drawGraph(points, furtherText = furtherText, origin = origin, boundary = True)


    def _returnSelectedFiles(self):
        "returns files that are chosen for creating of images"
        which = self.saveWhichFilesVar.get()
        
        files = []
        if which == "all":
            files.extend(self.fileStorage.arenafiles)
        elif which == "tagged":
            files.extend(self.fileStorage.tagged)
        elif which == "untagged":
            files.extend([file for file in self.fileStorage.arenafiles if file not in
                          self.fileStorage.tagged])
        elif which == "current":
            files = [self.fileFrame.selected]

        return files
            

    def toggleAnimation(self):
        "called when checkbutton for showing tracks is toggled"
        if self.initialized:          
            self.initializeFile(self.fileFrame.selected, new = False, timeReset = False)


    def toggleReflections(self):
        "called when reflections removal is changed - just refreshes canvases"
        if self.initialized:          
            if self.removeReflectionsVar.get():
                self.cm.removeReflections(points = self.fileStorage.reflections.get(self.cm.nameA,
                                                                                    None))
                self.data = self.cm.getData()
                self.initializeFile(self.fileFrame.selected, new = False, timeReset = False)
            else:
                self.initializeFile(self.fileFrame.selected, new = True, timeReset = False)


    def toggleShocks(self):
        "called when checkbutton for showing shocks is toggled"
        if self.initialized and self.showTrackVar.get():
            self.initializeFile(self.fileFrame.selected, new = False, timeReset = False)                    
            

    def playFun(self):
        "starts animation"        
        self.timeFrame.changeState("disabled")
        self.showTrack["state"] = "disabled"
        self.saveBut.state(["disabled"])
        self.animate = "" # status of the animation - '', 'pause', 'stop'
        
        prevTime = time()
        while not self.animate:
            # finds current time
            nowTime = time()
            difTime = (nowTime - prevTime) * 1000
            playTime = difTime * self.speed.get() + (
                self.curTime.get() * (self.maxTime - self.minTime) / 100) + self.minTime

            if playTime > self.maxTime:
                self.curTime.set(100)
                self.timeVar.set(self._timeFormat(self.maxTime))  
                self.animate = "stop"
                self.timeFrame.changeState("!disabled")
                self.showTrack["state"] = "!disabled"
                self.saveBut.state(["!disabled"])
                break

            self.changedTime(playTime, unit = "ms")

            prevTime = nowTime


    def changedTime(self, value, unit = "0-100"):
        "called when time is changed"
        if not self.initialized or self.minTime > self.maxTime or self.maxTime < self.minTime:
            return
        
        if unit == "ms":
            value = value
        else:
            value = ((float(value) * (self.maxTime - self.minTime)) / 100) + self.minTime
        
        # finds current line in data and computes current distance and entrances            
        x0, y0 = self.data[0][7:9] 
        dist = 0
        entrances = 0
        prev = 0
        skip = 25 # z options
        start = self.cm.findStart(self.minTime / 60000)
        for row, content in enumerate(self.data[start:]):
            if content[1] < value:
                # distance
                if row % skip == 0:
                    x1, y1 = content[7:9]
                    diff = ((x1 - x0)**2 + (y1 - y0)**2)**0.5
                    dist += diff
                    x0, y0 = x1, y1
                # entrances
                if content[5] != 2 and prev != 2:
                    continue
                elif content[5] != 2 and prev == 2:
                    if content[5] == 0: 
                        prev = 0
                    continue
                elif content[5] == 2 and prev == 2:
                    continue
                elif content[5] == 2 and prev != 2:
                    entrances += 1
                    prev = 2
                    continue
            else:
                curLine = content
                break
        dist = dist / (self.cm.trackerResolution * 100) # conversion from pixels to metres
        self.distanceVar.set("{:.1f}".format(dist))
        self.entrancesVar.set(entrances)

        Rx, Ry = curLine[2:4]
        Ax, Ay = curLine[7:9]                              

        # changes position of 'the rat'
        self.arenaCanv.coords("ratA", (Ax + self.ld, Ay + self.ld,\
                                Ax + self.ur, Ay + self.ur))
        self.roomCanv.coords("ratR", (Rx + self.ld, Ry + self.ld,\
                                Rx + self.ur, Ry + self.ur))

        # changes color of 'the rat' in case of shock
        if curLine[6] > 0:
            self.roomCanv.itemconfigure("ratR", fill = "red", outline = "red")
            self.shock = True
        elif self.shock and curLine[6] <= 0:
            self.roomCanv.itemconfigure("ratR", fill = "black", outline = "black")
            self.shock = False       

        self.graph.changedTime(value)

        # changes position of a time scale               
        if value < self.maxTime:
            self.curTime.set(((value - self.minTime) * 100) / (self.maxTime - self.minTime))
            self.timeVar.set(self._timeFormat(value))  
        else:
            self.curTime.set(100)
            self.timeVar.set(self._timeFormat(self.maxTime))          

        self.update()

            
    def setTime(self):
        "called when maximum or minimum time is set"
        if self.initialized:
            nowTime = (self.curTime.get() / 100) * (self.maxTime - self.minTime) + self.minTime
            self.initializeFile(self.fileFrame.selected, new = False)
            if self.minTime <= nowTime <= self.maxTime:
                self.graph.changedTime(nowTime)
                self.changedTime(nowTime, unit = "ms")
            elif self.minTime > nowTime:
                self.graph.changedTime(self.minTime)
                self.changedTime(self.minTime, unit = "ms")
            else:
                self.graph.changedTime(self.maxTime)
                self.changedTime(self.maxTime, unit = "ms")
            

    def pauseFun(self):
        "pauses and unpauses animation"
        if self.animate == "pause":
            self.timeFrame.changeState("disabled")
            self.showTrack["state"] = "disabled"
            self.saveBut.state(["disabled"])
            self.playFun()
        else:
            self.animate = "pause"
            self.timeFrame.changeState("!disabled")        
            self.showTrack["state"] = "!disabled"
            self.saveBut.state(["!disabled"])
            

    def stopFun(self):
        "stops animation"
        self.animate = "stop"
        self.changedTime(0)
        self.timeFrame.changeState("!disabled")          
        self.showTrack["state"] = "!disabled"
        self.saveBut.state(["!disabled"])
        

    def initializeFile(self, filename, new = True, timeReset = True):
        "initializes canvases, graph, etc."
        if new:
            try:
                if filename in self.fileStorage.pairedfiles:
                    self.cm = CM(filename, nameR = self.fileStorage.pairedfiles[filename])
                else:
                    self.cm = CM(filename, nameR = "auto")
                if self.removeReflectionsVar.get():
                    self.cm.removeReflections(points = self.fileStorage.reflections.get(filename,
                                                                                        None))
                self.data = self.cm.getData()
            except Exception as e:
                if optionGet("Developer", False, 'bool'):
                    print(e)
                self.status.set("File failed to load!")
                self.bell()
                return

  
        # initialization of canvases
        self.arenaCanv.delete("all")
        self.roomCanv.delete("all")
        
        d = self.cm.getComputedDiameter()
        self.arenaCanv.create_oval(150 - d, 150 - d, 150 + d, 150 + d, outline = "black",\
                                   width = 2, tags = "arenaAF")
        self.roomCanv.create_oval(150 - d, 150 - d, 150 + d, 150 + d, outline = "black",\
                                  width = 2, tags = "arenaRF")

       
        # creates lines depicting the shock sector
        if self.cm.getCenterAngle():
            self.angle = self.cm.getCenterAngle()
            self.width = self.cm.getWidth()

            a1 = radians(self.angle - (self.width / 2))
            a2 = radians(self.angle + (self.width / 2))

            Sx1, Sy1 = 150 + (cos(a1) * d), 150 - (sin(a1) * d)
            Sx2, Sy2 = 150 + (cos(a2) * d), 150 - (sin(a2) * d)
            
            self.roomCanv.create_line((Sx1, Sy1, 150, 150, Sx2, Sy2), fill = "red", width = 2,\
                                       tags = "shockZone")


        # minimal and maximal time
        self.maxTime = min([self.cm.data[-1][1], eval(self.timeFrame.timeVar.get()) * 60000])
        self.minTime = max([self.cm.data[0][1], eval(self.timeFrame.startTimeVar.get()) * 60000])

        # initial position
        for line in self.data:
            if line[1] < self.minTime:
                continue                       
            else:
                curLine = line
                break
        else:
            self.status.set("Invalid start time set.")
            self.bell()
            return

        
        if self.showTrackVar.get():
            # draws tracks        
            data = [line[2:4] + line[6:9] for count, line in enumerate(self.data) if
                    self.minTime <= line[1] <= self.maxTime]
            arena = []
            room = []
            prev = [-100, -100, 0, -100, -100]
            last = [0, 0]
            for count, line in enumerate(data):
                if abs(line[0] - prev[0]) + abs(line[1] - prev[1]) > 2 or count - last[0] == 15 or\
                   line[2] > 0:
                    room.append(line[0:2])
                    last[0] = count
                if abs(line[3] - prev[3]) + abs(line[4] - prev[4]) > 2 or count - last[1] == 15:
                    arena.append(line[3:5])
                    last[1] = count
                prev = line
                    
            self.arenaCanv.create_line(([item + 150 - d for line in arena for item in line]),
                                       fill = "black", width = 2)
            self.roomCanv.create_line(([item + 150 - d for line in room for item in line]),
                                      fill = "black", width = 2)
            # draws shocks
            if self.showShocksVar.get():
                shocks = [line[2:4] for count, line in enumerate(self.data) if
                          self.minTime <= line[1] <= self.maxTime and line[6] > 0 and
                          self.data[count - 1][6] <= 0]
                self.ld = 150 - d - 4
                self.ur = 150 - d + 4
                for shock in shocks:
                    self.roomCanv.create_oval(shock[0] + self.ld, shock[1] + self.ld,
                                              shock[0] + self.ur, shock[1] + self.ur,
                                              outline = "red", width = 3)
        else:
            # makes 'the rat' (i.e. two black points)
            self.ld = 150 - d - 4 # 4 is size of the rat dot
            self.ur = 150 - d + 4
            
            Rx, Ry = curLine[2:4]
            Ax, Ay = curLine[7:9]
            self.arenaCanv.create_oval(Ax + self.ld, Ay + self.ld, Ax + self.ur, Ay + self.ur,\
                                       fill = "black", tags = "ratA")
            self.roomCanv.create_oval(Rx + self.ld, Ry + self.ld, Rx + self.ur, Ry + self.ur,\
                                       fill = "black", tags = "ratR")
            
            # shock
            if curLine[6] > 0:
                self.roomCanv.itemconfigure("ratR", fill = "red", outline = "red")
                self.shock = True   
            else:
                self.shock = False


        # initializes distance and entrances displays
        self.totDistanceVar.set(round(self.cm.getDistance(time = self.maxTime / 60000,
                                                          startTime = self.minTime / 60000), 1))
        self.totEntrancesVar.set(self.cm.getEntrances(time = self.maxTime / 60000,
                                                      startTime = self.minTime / 60000))
        if timeReset:
            self.distanceVar.set("0.0")
            self.entrancesVar.set("0")


        # drawing of the graph
        self.graph.delete("all")
        if timeReset:
            self.graph.CM_loaded(self.cm, minTime = self.minTime, maxTime = self.maxTime)
        else:
            self.graph.CM_loaded(self.cm, minTime = self.minTime, maxTime = self.maxTime,
                                 initTime = (self.curTime.get() * (self.maxTime - self.minTime) /
                                             100 + self.minTime))

    
        # changing buttons' statuses
        if not self.showTrackVar.get():
            self.playBut.state(["!disabled"])
            self.pauseBut.state(["!disabled"])
            self.stopBut.state(["!disabled"])
            self.timeSc.state(["!disabled"])
        else:
            self.playBut.state(["disabled"])
            self.pauseBut.state(["disabled"])
            self.stopBut.state(["disabled"])
            self.timeSc.state(["disabled"])


        self.initialized = True


        if new and timeReset:
            self.curTime.set(0)
            self.timeVar.set(self._timeFormat(self.minTime))  


        
    def changedGraph(self):
        "called when the graph is changed"
        self.graph.delete("all")
        drawnParameter = self.graph.drawnParameter
        self.graph = eval(self.graphTypeVar.get())
        self.graph.drawnParameter = drawnParameter
        self.graph.grid(column = 0, row = 4, columnspan = 7, padx = 2, pady = 5, sticky = (E, W))
        self.graph.bind("<Button-1>", self.graphClick)
        self.graph.bind("<Button-3>", self.graphPopUp)
        if self.initialized:
            self.graph.CM_loaded(self.cm, minTime = self.minTime, maxTime = self.maxTime,
                                 initTime = ((self.curTime.get() * (self.maxTime - self.minTime) /
                                              100) + self.minTime))
            

    def graphClick(self, event):
        "changes time when the graph is clicked upon"
        if self.initialized and not self.showTrackVar.get():
            self.graph.coords("timeMeasure", (event.x, 0, event.x, self.graph.height))
            time = (event.x * 100) / self.graph.width
            if time > 100:
                time = 100           
            self.changedTime(time)


    def graphPopUp(self, event):
        "shows menu for selection of parameter to be shown in graph"
        if not self.initialized:
            return
        
        menu = Menu(self, tearoff = 0)
        menu.add_command(label = "Show periodicity",
                         command = lambda: self.graph.drawParameter(self.cm, "periodicity"))
        menu.add_command(label = "Show mobility",
                         command = lambda: self.graph.drawParameter(self.cm, "mobility"))
        menu.add_command(label = "Show immobility",
                         command = lambda: self.graph.drawParameter(self.cm, "immobility"))
        menu.add_command(label = "Show entrances",
                         command = lambda: self.graph.drawParameter(self.cm, "entrances"))
        menu.add_command(label = "Show shocks",
                         command = lambda: self.graph.drawParameter(self.cm, "shocks"))
        menu.add_command(label = "Show bad points",
                         command = lambda: self.graph.drawParameter(self.cm, "bad points"))
        menu.add_command(label = "Show thigmotaxis",
                         command = lambda: self.graph.drawParameter(self.cm, "thigmotaxis"))
        menu.add_command(label = "Don't show anything",
                         command = lambda: self.graph.drawParameter(self.cm, None))
        menu.post(event.x_root, event.y_root)        


    def unDraw(self):
        "clears canvases, graph etc."
        if self.initialized:
            self.arenaCanv.delete("all")
            self.roomCanv.delete("all")
            self.graph.delete("all")
            self.initialized = False
            self.playBut.state(["disabled"])
            self.pauseBut.state(["disabled"])
            self.stopBut.state(["disabled"])
            self.fileFrame.previousBut.state(["disabled"])
            self.fileFrame.nextBut.state(["disabled"])
            self.fileFrame.tagBut.state(["disabled"])
            self.saveBut.state(["disabled"])
            

    def checkProcessing(self):
        "called when content of fileStorage is changed"
        if self.fileStorage.arenafiles or self.fileStorage.wrongfiles:
            self.fileStorageFrame.removeFiles.state(["!disabled"])
        else:
            self.fileStorageFrame.removeFiles.state(["disabled"])
        self.fileStorageFrame.chosenVar.set(len(self.fileStorage.arenafiles))
        self.fileStorageFrame.nonMatchingVar.set(len(self.fileStorage.wrongfiles))

        self.fileFrame.files = [] + self.fileStorage.arenafiles
        
        if not self.fileFrame.files or not self.fileFrame.selected in self.fileFrame.files:
            self.unDraw()

        if self.fileFrame.files:
            self.fileFrame.previousBut.state(["!disabled"])
            self.fileFrame.nextBut.state(["!disabled"])
            self.fileFrame.tagBut.state(["!disabled"])
            self.saveBut.state(["!disabled"])
            if not self.fileFrame.selected in self.fileFrame.files:
                self.fileFrame.selected = None
        else:
            self.fileFrame.selected = None
            
        self.fileFrame.drawTree(self.fileFrame.selected)


    def initialize(self):
        """initializes the canvases etc. if files were added to fileStorage and file from
            fileStorage is not initialized"""
        if self.fileFrame.files:
            if not self.fileFrame.selected in self.fileFrame.files:
                self.initializeFile(self.fileFrame.files[0])
                self.fileFrame.selected = self.fileFrame.files[0]


    def _timeFormat(self, time):
        "formats time from miliseconds to minutes:seconds"
        minutes = time // 60000
        seconds = (time % 60000) // 1000
        return "{:d}:{:0>2d}".format(int(minutes), int(seconds))

         
    def changedSpeed(self, value):
        "rounds speed set by scale"
        if eval(value) <= 1.0:
            self.speed.set(round(self.speed.get(), 1))
        elif eval(value) < 2.0:
            self.speed.set(round(self.speed.get() * 5, 0) / 5)
        elif eval(value) < 5.0:
            self.speed.set(round(self.speed.get() * 2, 0) / 2)
        elif eval(value) < 10.0:
            self.speed.set(round(self.speed.get(), 0))
        else:
            self.speed.set(round(self.speed.get() * 5, -1) / 5)
コード例 #19
0
class Processor(ttk.Frame):
    "represents 'Process' page in the main window notebook"
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (10, 10, 12, 12)
        self.root = root
        self.fileStorage = self.root.fileStorage
        self.selectedBatchTime = optionGet("LastBatchTime", [(0, 20)], "list") # zkontrolovat ""

        # variables    
        self.status = StringVar()
        self.useBatchTimeVar = BooleanVar()
              
        # frames
        self.parametersF = ParameterFrame(self)
        self.fileStorageFrame= FileStorageFrame(self)
        self.saveToFrame = SaveToFrame(self, parent = "processor")
        self.optionFrame = OptionFrame(self, text = "Options")
        self.timeLabFrame = ttk.Labelframe(self, text = "Time")
        self.timeLabFrame.root = self
        self.timeFrame = TimeFrame(self.timeLabFrame)
        
        # buttons
        self.process = ttk.Button(self, text = "Process Files", command = self.processFun,
                                  state = "disabled")
        self.useBatchTime = ttk.Checkbutton(self.timeLabFrame, text = "Use batch time",
                                            variable = self.useBatchTimeVar,
                                            command = self.toggledUseBatchTime)
        self.setBatchTimeBut = ttk.Button(self.timeLabFrame, text = "Set", width = 3,
                                          command = self.setBatchTime)

        # labels
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.modeLab = ttk.Label(self, text = m.fullname[m.mode], font = ("Helvetica", "16"))
       
        # adding to grid
        self.parametersF.grid(column = 0, row = 3, columnspan = 4, sticky = (N, W), padx = 4)
        self.fileStorageFrame.grid(column = 3, row = 0, pady = 5, padx = 4)
        self.timeLabFrame.grid(column = 1, row = 5, padx = 30, sticky = (N, W))
        self.timeFrame.grid(column = 0, row = 0, columnspan = 2, sticky = (E, W))
        
        self.process.grid(column = 3, row = 7, sticky = (S, E), padx = 4, pady = 3)
        self.useBatchTime.grid(column = 0, row = 1, pady = 5)
        self.setBatchTimeBut.grid(column = 1, row = 1, pady = 5)

        self.statusBar.grid(column = 0, row = 7, columnspan = 3, sticky = (N, S, E, W), padx = 6,
                            pady = 3)
        self.modeLab.grid(column = 0, row = 0)
       
        self.saveToFrame.grid(column = 1, row = 1, columnspan = 3, sticky = (N, S, E, W),
                              padx = 6, pady = 2)

        self.optionFrame.grid(column = 0, row = 5, sticky = (N, E), padx = 6)
  
        # what should be enlarged
        self.columnconfigure(2, weight = 1)
        self.rowconfigure(2, weight = 3)
        self.rowconfigure(4, weight = 2)
        self.rowconfigure(6, weight = 2)


    def processCheck(self):
        "checks whether all inputs are valid - helper function for processFun"

        if self.saveToFrame.saveToVar.get() == "":
            raise Exception("You have to choose an output file!")
        
        if len(self.fileStorage) == 0:
            raise Exception("You haven't chosen any file!")

        try:
            startTime = float(self.timeFrame.startTimeVar.get())
        except Exception:
            raise Exception("Start time has to be a number!")
        try:
            time = float(self.timeFrame.timeVar.get())
        except Exception:
            raise Exception("Stop time has to be a number!")
        
        if startTime >= time:
            raise Exception("Start time must be smaller than stop time!")

        if time < 0 or startTime < 0:
            raise Exception("Time has to be set to a positive value")

        if not os.path.exists(os.path.split(self.saveToFrame.saveToVar.get())[0]):
            if os.path.split(self.saveToFrame.saveToVar.get())[0]:
                raise Exception("Pathname of the output file doesn't exist!")
            
        if len(self.filesToProcess) == 0:
            raise Exception("There is no file selected for processing!")
      
        
    def processFun(self):
        "processes chosen files and saves the results in the save-to file"
        # files to be processed
        self.filesToProcess = [file for file in self.fileStorage if \
                               self.optionFrame.processFile(file)]

        # checking for mistakes
        try:
            self.processCheck()
        except Exception as e:
            self.bell()
            self.status.set(e)
            return                   

        # progressWindow
        if len(self.filesToProcess) > 1:
            self.stoppedProcessing = False
            self.progressWindow = ProgressWindow(self, len(self.filesToProcess))     

        # initializations
        output = self.saveToFrame.saveToVar.get()
        if not os.path.splitext(output)[1]:
            output = output + optionGet("DefProcessOutputFileType", ".txt", "str", True)
        if not os.path.dirname(output):
            output = os.path.join(optionGet("ResultDirectory", os.getcwd(), "str", True), output)
        startTime = float(self.timeFrame.startTimeVar.get())
        time = float(self.timeFrame.timeVar.get())
        separator = optionGet("ResultSeparator", ",", "str", True)
        batchTime = self.selectedBatchTime if self.useBatchTimeVar.get() else None
        self.someProblem = False
        developer = optionGet("Developer", False, 'bool', True)

        # selected methods          
        methods = OrderedDict()
        parameters = m.parameters
        for name, par in parameters.items():
            if eval("self.parametersF.%sVar.get()" % (name.replace(" ", ""))):
                options = {name: optionGet(*option[0]) for name, option in par.options.items()}
                if not self.useBatchTimeVar.get():
                    methods[name] = [methodcaller(par.method, startTime = startTime,
                                                  time = time, **options)]
                elif name not in parameters.noBatch:
                    methods[name] = [methodcaller(par.method, startTime = times[0],
                                                  time = times[1], **options)
                                     for times in batchTime]
                else:
                    methods[name] = [methodcaller(par.method, **options)]

        # log
        self.log = Log(methods, startTime, time, self.filesToProcess, self.fileStorage,
                       self.optionFrame.removeReflectionsWhere.get(), output,
                       batchTime = batchTime)
                    
        # results header
        if self.useBatchTimeVar.get():
            results = ["File"]
            for method in methods:
                if method in parameters.noBatch:
                    results.append(method)
                else:
                    results.extend([method + " ({}-{})".format(start, end) for
                                    start, end in self.selectedBatchTime])
            results = separator.join(results)
        else:
            results = separator.join(["File"] + [method for method in methods])
        if self.optionFrame.saveTags.get():
            results += separator + "Tag"
        if self.optionFrame.saveComments.get():
            results += separator + "Comment"
        
        # computing of results
        for file in self.filesToProcess:
            # loading of cm object
            if methods:
                try:
                    if file in self.fileStorage.pairedfiles:
                        cm = m.CL(file, self.fileStorage.pairedfiles[file])
                    else:
                        cm = m.CL(file, "auto")

                    if self.optionFrame.removeReflections(file):
                        cm.removeReflections(points = self.fileStorage.reflections.get(file,
                                                                                            None))
                except Exception as e:
                    if developer:
                        print(e)   
                    filename = returnName(filename = file, allFiles =
                                          self.fileStorage.arenafiles) 
                    results += "\n" + filename + "{}NA".format(separator) * len(methods)
                    self.log.failedToLoad.append(file)
                    self.someProblem = True
                    continue
                                
            result = []

            for name, funcs in methods.items():
                for func in funcs:                        
                    try:
                        #if method[2] == "custom":
                            #exec("from Stuff.Parameters import {}".format(method[5]))               
                        result.append(func(cm))
                    except Exception as e:
                        if developer:
                            print(e)   
                        result.append("NA")
                        self.log.methodProblems[name].append(file)
                        self.someProblem = True

            result = separator.join(map(str, result))
            if methods:
                result = separator + result               
            filename = returnName(filename = file, allFiles = self.fileStorage.arenafiles)      
            results += "\n" + filename + result
            
            # tag inclusion in results
            if self.optionFrame.saveTags.get(): 
                if file in self.fileStorage.tagged:
                    results += separator + "1"
                else:
                    results += separator + "0"

            # comment inclusion in results
            if self.optionFrame.saveComments.get():
                results += separator + self.fileStorage.comments[file]
                    
            # progress window update
            if len(self.filesToProcess) > 1:
                if self.stoppedProcessing:
                    writeResults(output, results)
                    self.log.stopped = file
                    self.log.writeLog()
                    self.status.set("Processing stopped")
                    return
                else:
                    self.progressWindow.addOne()

        # results and log writing, ending of processing
        writeResults(output, results)
        self.log.writeLog()
        self._setStatusEndProgressWindow()

        if self.someProblem:
            ProcessingProblemDialog(self, self.log.filename, output)
        elif self.optionFrame.showResults.get():
            os.startfile(output)   

            
    def _setStatusEndProgressWindow(self):
        if len(self.filesToProcess) > 1:
            if self.someProblem:
                self.status.set("Files were processed.")
            else:
                self.status.set("Files were processed successfully.")
            self.progressWindow.destroy()
        else:
            if self.someProblem:
                self.status.set("File was processed.")
            else:
                self.status.set("File was processed successfully.")        


    def toggledUseBatchTime(self):
        "called when batch time checkbutton is toggled; disables or enables changing time"
        if self.useBatchTimeVar.get():
            self.timeFrame.totalTime.state(["disabled"])
            self.timeFrame.startTime.state(["disabled"])
        else:
            self.timeFrame.totalTime.state(["!disabled"])
            self.timeFrame.startTime.state(["!disabled"])


    def setBatchTime(self):
        SetBatchTime(self)
        if not self.useBatchTimeVar.get():
            self.useBatchTimeVar.set(True)
            self.toggledUseBatchTime()        

                
    def checkProcessing(self):
        "method updating page after change of notebook tab"
        if self.fileStorage.arenafiles and self.saveToFrame.saveToVar.get():
            self.process.state(["!disabled"])
        else:
            self.process.state(["disabled"])

        if self.fileStorage.arenafiles or self.fileStorage.wrongfiles:
            self.fileStorageFrame.removeFiles.state(["!disabled"])
        else:
            self.fileStorageFrame.removeFiles.state(["disabled"])        

        self.fileStorageFrame.chosenVar.set(len(self.fileStorage))
        self.fileStorageFrame.nonMatchingVar.set(len(self.fileStorage.wrongfiles))
コード例 #20
0
class FileTree(ttk.Frame):
    "displays files in ShowTracks class"
    def __init__(self, root, files, time = "auto", controlled = False):
        super().__init__(root)

        self.rowconfigure(0, weight = 1)

        self.allFiles = files # used when un-selecting files
        self.files = files # currently diplayed files
        self.controlled = controlled # True if FileTree called from controller
        self.root = root
        self.fileStorage = self.root.fileStorage
        self.index = self.root.index # which file is selected when the FileTree is initialized
        self.usedProblemOrder = -1 # by which method is the tree ordered (index)
        if time == "auto":
            time = (0, 20)

        # tree
        self.treeFrame = ttk.Frame(self)
        self.treeFrame.grid(column = 0, row = 0, columnspan = 3, sticky = (N, S, E, W))
        self.treeFrame.rowconfigure(0, weight = 1)
        self.treeFrame.columnconfigure(0, weight = 1)
        
        self.tree = ttk.Treeview(self.treeFrame, selectmode = "browse", height = 20)
        self.tree.grid(column = 0, row = 0, sticky = (N, S, E, W))
        
        if self.controlled:
            columns = ("problem", "tag")
        else:
            columns = ("tag")
        self.tree["columns"] = columns

        self.tree.column("#0", width = 240, anchor = "w")        
        self.tree.heading("#0", text = "File", command = self.orderByNames)

        self.tree.column("tag", width = 40, anchor = "center")
        self.tree.heading("tag", text = "Tag", command = self.orderByTag)
        
        if self.controlled:
            self.tree.column("problem", width = 160, anchor = "e")
            self.tree.heading("problem", text = "Problems", command = self.orderByProblem)
            
        self.scrollbar = ttk.Scrollbar(self.treeFrame, orient = VERTICAL,
                                       command = self.tree.yview)
        self.scrollbar.grid(column = 1, row = 0, sticky = (N, S, E))
        self.tree.configure(yscrollcommand = self.scrollbar.set)

        self.tree.bind("<1>", lambda e: self.click(e))
        self.tree.bind("<3>", lambda e: self.popUp(e))

        self.drawTree()

        # bottom frame
        self.bottomFrame = ttk.Frame(self)
        self.bottomFrame.grid(column = 0, row = 1, columnspan = 2)
        self.bottomFrame.columnconfigure(3, weight = 1)
        self.bottomFrame.rowconfigure(1, weight = 1)

        # previous and next buttons
        self.fileLabFrame = ttk.Labelframe(self.bottomFrame, text = "File")
        self.fileLabFrame.grid(column = 0, row = 0, sticky = (N, W), pady = 3, padx = 1)
        
        self.previousBut = ttk.Button(self.fileLabFrame, text = "Previous",
                                      command = self.previousFun)
        self.previousBut.grid(column = 0, row = 0, padx = 3)
        
        self.nextBut = ttk.Button(self.fileLabFrame, text = "Next", command = self.nextFun)
        self.nextBut.grid(column = 1, row = 0, padx = 3)

        # tag buttons
        self.tagLabFrame = ttk.Labelframe(self.bottomFrame, text = "Tagging")
        self.tagLabFrame.grid(column = 0, row = 1, sticky = (N, W), rowspan = 2,
                              padx = 1, pady = 4)
        
        self.tagBut = ttk.Button(self.tagLabFrame, text = "Tag file", command = self.tagFun)
        self.tagBut.grid(column = 1, row = 1, padx = 3)
        self.checkTag()

        self.tagAllBut = ttk.Button(self.tagLabFrame, text = "Tag all", command = self.tagAllFun)
        self.tagAllBut.grid(column = 2, row = 1, padx = 3)

        self.untagAllBut = ttk.Button(self.tagLabFrame, text = "Remove all tags",
                                      command = self.untagAllFun)
        self.untagAllBut.grid(column = 3, row = 1, padx = 3)

        # time frame
        self.timeLabFrame = ttk.Labelframe(self.bottomFrame, text = "Time")
        self.timeLabFrame.grid(column = 3, row = 0, rowspan = 2, sticky = N, pady = 3)
        self.timeLabFrame.root = self.root
        
        self.timeFrame = TimeFrame(self.timeLabFrame, onChange = True)
        self.timeFrame.grid(column = 0, row = 0)
        self.timeFrame.timeVar.set(time[1])
        self.timeFrame.startTimeVar.set(time[0])

        # remove reflections checkbutton
        self.removeReflectionsVar = BooleanVar()
        self.removeReflectionsVar.set(False)
        self.removeReflections = ttk.Checkbutton(self.bottomFrame, text = "Remove reflections",
                                                 variable = self.removeReflectionsVar,
                                                 command = self.toggleReflections)
        self.removeReflections.grid(column = 2, row = 2, padx = 7, pady = 5, sticky = (N, W),
                                    columnspan = 2)

        # frame radiobuttons       
        self.frameFrame = ttk.Labelframe(self.bottomFrame, text = "Frame")
        self.frameFrame.grid(column = 2, row = 0, padx = 5, rowspan = 2, pady = 3, sticky = N)

        self.frameVar = StringVar()
        self.frameVar.set("arena")
        
        self.arenaFrameRB = ttk.Radiobutton(self.frameFrame, text = "Arena",
                                            variable = self.frameVar, value = "arena",
                                            command = self.toggleFrame)
        self.arenaFrameRB.grid(column = 0, row = 0, pady = 2)
        
        self.roomFrameRB = ttk.Radiobutton(self.frameFrame, text = "Room",
                                           variable = self.frameVar, value = "room",
                                           command = self.toggleFrame)
        self.roomFrameRB.grid(column = 0, row = 1, pady = 2)



    def toggleFrame(self):
        "called when frame is changed - just refreshes canvases"
        self.root.drawTracks(new = False)


    def toggleReflections(self):
        "called when reflections removal is changed - just refreshes canvases"
        if self.removeReflectionsVar.get():
            self.root.drawTracks(new = False)
        else:
            self.root.drawTracks(new = True)            
        

    def tagAllFun(self):
        "tags all displayed files"
        for file in self.files:
            self.fileStorage.tag(file)
        self.drawTree()
        self.tagBut["text"] = "Remove tag"
        self.tagBut["command"] = self.untagFun

    def untagAllFun(self):
        "untags all displayed files"
        for file in self.files:
            if file in self.fileStorage.tagged:
                self.fileStorage.tagged.remove(file)
        self.drawTree()
        self.tagBut["text"] = "Tag file"
        self.tagBut["command"] = self.tagFun        

    def tagFun(self, index = "none"):
        "tags the selected file"
        selected = self.files[eval(self.tree.selection()[0])]
        if index != "none":
            self.index = index
        else:
            self.tagBut["text"] = "Remove tag"
            self.tagBut["command"] = self.untagFun
        self.fileStorage.tag(self.files[self.index])
        self.drawTree(selected = selected)

    def untagFun(self, index = "none"):
        "untags the selected file"
        selected = self.files[eval(self.tree.selection()[0])]
        if index != "none":
            self.index = index
        else:
            self.tagBut["text"] = "Tag file"
            self.tagBut["command"] = self.tagFun 
        self.fileStorage.tagged.remove(self.files[self.index])
        self.drawTree(selected = selected)              

    def checkTag(self):
        "checks the state of tag button"
        if self.files[self.index] in self.fileStorage.tagged:
            command = self.untagFun
            text = "Remove tag"
        else:
            command = self.tagFun
            text = "Tag file"            
        self.tagBut["text"] = text
        self.tagBut["command"] = command


    def click(self, event):
        "called when item in tree is clicked"
        item = self.tree.identify("item", event.x, event.y)
        if item:
            self.tree.selection_set(item)
            self.index = int(item)
            self.root.drawTracks(new = True)
            self.checkTag()

        
    def previousFun(self):
        "shows previous file"
        if self.index != 0:
            self.prevIndex = self.index
            self.index -= 1
            self.root.drawTracks(new = True)
            self.tree.selection_set(str(self.index))
            self.tree.see(str(self.index))
            self.checkTag()

    def nextFun(self):
        "shows next file"
        if self.index != len(self.files) - 1:
            self.prevIndex = self.index
            self.index += 1
            self.root.drawTracks(new = True)
            self.tree.selection_set(str(self.index))
            self.tree.see(str(self.index))
            self.checkTag()


    def orderByNames(self):
        "orders files by names"
        selected = self.files[eval(self.tree.selection()[0])]
        self.files.sort()
        self.drawTree(selected = selected)

    def orderByTag(self):
        "order files by tags"
        selected = self.files[eval(self.tree.selection()[0])]
        self.files.sort(key = lambda i: (i in self.fileStorage.tagged),
                        reverse = True)
        self.drawTree(selected = selected)

    def orderByProblem(self):
        """orders files by problem - which is displayed (the problem by which files are ordered
            changes when the function is used again)"""
        selected = self.files[eval(self.tree.selection()[0])]
        self.usedProblemOrder = (self.usedProblemOrder + 1) % \
                                len(self.root.root.controlReport.controls)
        method = self.root.root.controlReport.controls[self.usedProblemOrder]
        results = self.root.root.controlReport.results[method]
        values = {tup[0]: tup[3] for tup in results}
        self.tree.heading("problem", text = ("Problems (by {})".format(method)))
        
        self.files.sort(key = lambda i: values[i], reverse = True)
        self.drawTree(selected = selected)


    def drawTree(self, selected = None):
        "initializes (or refreshes) tree"
        for child in self.tree.get_children():
            self.tree.delete(child)
            
        for count, file in enumerate(self.files):
            if file in self.fileStorage.tagged:
                tag = "x"
            else:
                tag = ""
                
            if self.controlled:
                problemKey = {"Problem": "P", "Warning": "W", "Concern": "C", "OK": "O"}
                methodKey = {"Reflections": "Ref", "Bad Points": "BP", "Outside Points": "OP"}
                problem = ""
                for method in self.root.root.controlReport.results:
                    importance = [i[2] for i in self.root.root.controlReport.results[method] if\
                                  i[0] == file]
                    problem = problem + methodKey[method] + ": " + problemKey[importance[0]] + ", "
                problem = problem[:-2]                  
                values = (problem, tag)
            else:
                values = (tag)
   
            self.tree.insert("", "end", str(count), text = returnName(file, self.files),
                             values = values)

        if selected:
            self.index = self.files.index(selected)

        if self.files:
            self.tree.selection_set(str(self.index))            
            self.tree.see(str(self.index))
            

    def popUp(self, event):
        "called when tree item is clicked on"
        item = self.tree.identify("item", event.x, event.y)
        menu = Menu(self, tearoff = 0)
        if item:
            if self.files[int(item)] in self.fileStorage.tagged:
                menu.add_command(label = "Remove tag", command = lambda: self.untagFun(index =
                                                                                       int(item)))
            else:
                menu.add_command(label = "Add tag", command = lambda: self.tagFun(index =
                                                                                  int(item)))
        elif self.controlled:
            menu.add_command(label = 'Leave only Bad Points', command = lambda:
                                 self.leaveOnlyFun("Bad Points"))        
            menu.add_command(label = 'Leave only Reflections', command = lambda:
                                 self.leaveOnlyFun("Reflections"))
            menu.add_command(label = 'Leave only Outside Points', command = lambda:
                                 self.leaveOnlyFun("Outside Points"))                       
            menu.add_command(label = "Return all", command = lambda: self.leaveOnlyFun("all"))
        menu.post(event.x_root, event.y_root)


    def leaveOnlyFun(self, problem):
        "leaves only files with some problem; or show all files again if problem == 'all'"
        if self.files:
            currentFile = self.files[self.index]
        else:
            currentFile = None
        
        if problem != "all":
            self.files = [file for file in self.files if file in 
                          [i[0] for i in self.root.root.controlReport.results[problem] if
                           i[2] != "OK"]]
        else:
            self.files = self.allFiles
            
        if currentFile in self.files:
            self.index = self.files.index(currentFile)
        else:    
            self.index = 0
            
        self.drawTree()
        
        if self.files:
            self.root.drawTracks()
            self.tree.selection_set(str(self.index))
            self.checkTag()
コード例 #21
0
class Controller(ttk.Frame):
    "represents 'Control' page in the main window notebook"
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (7, 7, 9, 9)

        self.root = root
        self.fileStorage = self.root.fileStorage

        # file selection
        self.saveToVar = StringVar()
        self.saveToVar.set(True)
        self.fileStorageFrame = FileStorageFrame(self)
        self.fileStorageFrame.grid(column = 1, row = 0, columnspan = 2, sticky = (N, S, E, W),
                                   pady = 5, padx = 2)

        # statusbar
        self.status = StringVar()
        
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.statusBar.grid(column = 0, row = 4, columnspan = 2, sticky = (S, E, W))
        
        # control button
        self.process = ttk.Button(self, text = "Control", command = self.controlFun)
        self.process.grid(column = 2, row = 4, sticky = E)
        self.process.state(["disabled"])
        
        # report
        self.reportFrame = ttk.LabelFrame(self, text = "Report")
        self.reportFrame.grid(column = 0, row = 0, rowspan = 4, sticky = (N, S, E, W), padx = 5)
        self.reportFrame.columnconfigure(0, weight = 1)
        self.reportFrame.rowconfigure(0, weight = 1)

        self.upFrame = ttk.Frame(self.reportFrame)
        self.upFrame.grid(column = 0, row = 0, columnspan = 2, sticky = (N, S, E, W))
        self.upFrame.columnconfigure(0, weight = 1)
        self.upFrame.rowconfigure(0, weight = 1)
        
        self.contentTree = ttk.Treeview(self.upFrame, selectmode = "none")
        self.contentTree.grid(column = 0, row = 0, sticky = (N, S, E, W))
        self.contentTree["columns"] = ("description", "importance", "tag")
        self.contentTree.column("#0", width = 250, anchor = "w")
        self.contentTree.heading("#0", text = "Problem",
                                 command = lambda: self.orderReport("name"))
        self.contentTree.column("description", width = 200, anchor = "e")
        self.contentTree.heading("description", text = "Description",
                                 command = lambda: self.orderReport("description"))
        self.contentTree.column("importance", width = 60, anchor = "e")
        self.contentTree.heading("importance", text = "Importance",
                                 command = lambda: self.orderReport("importance"))
        self.contentTree.column("tag", width = 10, anchor = "center")
        self.contentTree.heading("tag", text = "Tag", command = lambda: self.orderReport("tag"))
        self.scrollbar = ttk.Scrollbar(self.upFrame, orient = VERTICAL,
                                       command = self.contentTree.yview)
        self.scrollbar.grid(column = 1, row = 0, sticky = (N, S, E))
        self.contentTree.configure(yscrollcommand = self.scrollbar.set)
        
        self.saveToFrame = SaveToFrame(self.reportFrame, label = False)
        self.saveToFrame.grid(column = 0, row = 1, sticky = (E, W))

        self.saveBut = ttk.Button(self.reportFrame, text = "Save", command = self.saveFun)
        self.saveBut.grid(column = 1, row = 1, sticky = E, padx = 2)
    
        self.controlReport = ControlReport(self)
                       
        self.contentTree.tag_bind("file", "<Double-1>", lambda e: self.treeDoubleClick(e))
        self.contentTree.tag_bind("file", "<3>", lambda e: self.filePopUp(e))
        self.contentTree.tag_bind("ok", "<3>", lambda e: self.okPopUp(e))
        self.contentTree.tag_bind("control", "<3>", lambda e: self.controlPopUp(e))
        self.contentTree.tag_configure("comment", background = commentColor())
        
        # method selection frame                
        self.controlFrame = ControlFrame(self)
        self.controlFrame.grid(column = 1, row = 1, columnspan = 2, sticky = (N, W), padx = 10,
                               pady = 55)

        # time frame
        self.timeFrame = TimeFrame(self)
        self.timeFrame.grid(column = 1, row = 2, columnspan = 2, sticky = (N, W), padx = 10)


        self.columnconfigure(0, weight = 1)
        self.rowconfigure(2, weight = 1)


    def orderReport(self, byWhat):
        "orders control report"
        opened = {}
        for child in self.contentTree.get_children():
            opened[child] = self.contentTree.item(child, "open")
            self.contentTree.delete(child)
        self.controlReport.orderedBy = byWhat
        self.controlReport.updateTree()
        for child in self.contentTree.get_children():
            if child in opened:
                self.contentTree.item(child, open=opened[child])


    def refresh(self):
        "refreshes the tree after adding a comment"
        self.controlReport.clear(clearAll = False)
        self.controlReport.updateTree()
        

    def filePopUp(self, event):
        "pop-up menu for file item in the tree"
        menu = Menu(self, tearoff = 0)
        item = self.contentTree.identify("item", event.x, event.y)
        name = item.rstrip("0123456789")
        if name in self.fileStorage.tagged:
            menu.add_command(label = "Remove tag", command = lambda: self.removeTag(name))
        else:
            menu.add_command(label = "Add tag", command = lambda: self.addTag(name))
        menu.add_command(label = "Add comment", command = lambda: Comment(self, name))
        menu.add_separator()
        menu.add_command(label = "Open arena file", command = lambda: self.openFile("arena", name))
        menu.add_command(label = "Open room file", command = lambda: self.openFile("room", name))
        menu.post(event.x_root, event.y_root)
        
    def controlPopUp(self, event):
        "pop-up menu for control item in the tree"
        menu = Menu(self, tearoff = 0)
        item = self.contentTree.identify("item", event.x, event.y)
        menu.add_command(label = "Add tags to all problem files",
                         command = lambda: self.addMoreTags(item, specified = ["Problem"]))
        menu.add_command(label = "Add tags to all files with at least a warning",
                         command = lambda: self.addMoreTags(item, specified =
                                                            ["Problem", "Warning"]))
        menu.add_command(label = "Add tags to all files with at least a concern",
                         command = lambda: self.addMoreTags(item, specified =
                                                            ["Problem", "Warning", "Concern"]))
        menu.add_separator()
        menu.add_command(label = "Remove tags from all problem files",
                         command = lambda: self.removeMoreTags(item, specified = ["Problem"]))
        menu.add_command(label = "Remove tags from all files with at least a warning",
                         command = lambda: self.removeMoreTags(item, specified =
                                                               ["Problem", "Warning"]))
        menu.add_command(label = "Remove tags from all files with at least a concern",
                         command = lambda: self.removeMoreTags(item, specified =
                                                               ["Problem", "Warning", "Concern"]))
        menu.post(event.x_root, event.y_root)
        
    def okPopUp(self, event):
        "pop-up menu for rest of files item in the tree"
        menu = Menu(self, tearoff = 0)
        item = self.contentTree.identify("item", event.x, event.y)
        menu.add_command(label = "Add tags to all OK files",
                         command = lambda: self.addMoreTags(item))
        menu.add_command(label = "Remove tags from all OK files",
                         command = lambda: self.removeMoreTags(item))
        menu.post(event.x_root, event.y_root)
        
    def openFile(self, frame, arenafile):
        "opens selected file; called from filePopUp"
        if frame == "room":
            if arenafile in self.fileStorage.pairedfiles:
                roomfile = self.fileStorage.pairedfiles[arenafile]
            else:
                if "Arena" in os.path.basename(arenafile):
                    splitName = os.path.split(arenafile)
                    roomfile = os.path.join(splitName[0], splitName[1].replace("Arena", "Room"))                    
                elif "arena" in os.path.basename(arenafile):
                    splitName = os.path.split(arenafile)
                    roomfile = os.path.join(splitName[0], splitName[1].replace("arena", "room"))
            if roomfile:
                os.startfile(roomfile)
            else:
                self.bell()
        elif frame == "arena":
            os.startfile(arenafile)

    def addTag(self, name):
        "adds tag to a single file"
        for num in range(len(self.controlReport.controls)):
            self.contentTree.set(name + str(num), "tag", "x")
        self.fileStorage.tag(name)
        
    def removeTag(self, name):
        "removes tag from a single file"
        for num in range(len(self.controlReport.controls)):
            self.contentTree.set(name + str(num), "tag", " ")
        self.fileStorage.tagged.remove(name)
        
    def addMoreTags(self, item, specified = False):
        "adds tags to more files; specified used for importance, e.g. ['Problem', 'Warning']"
        num = self.contentTree.index(item)
        for child in self.contentTree.get_children(item):
            name = child.rstrip("0123456789")
            if specified and not self.contentTree.set(name + str(num), "importance") in specified:
                next
            else:
                self.addTag(name)

    def removeMoreTags(self, item, specified = False):
        "removes tags to more files; specified used for importance, e.g. ['Problem', 'Warning']"
        num = self.contentTree.index(item)
        for child in self.contentTree.get_children(item):
            name = child.rstrip("0123456789")
            if specified and not self.contentTree.set(name + str(num), "importance") in specified:
                next
            else:
                if name in self.fileStorage.tagged:
                    self.removeTag(name)    

       
    def treeDoubleClick(self, event):
        "shows tracks in a ShowTracks toplevel window"
        item = self.contentTree.identify("item", event.x, event.y)
        name = item.rstrip("0123456789")
        tracks = self.controlReport.files # <- zmenit aby zobrazovalo serazene
        if item:
            showTracks = ShowTracks(self, nameA = name, tracks = tracks, controlled = True)


    def controlFun(self):
        "processes selected files, clears report, shows results in a report"

        # progressbar
        if len(self.fileStorage) > 1:
            self.stoppedProcessing = False
            self.progressWindow = ProgressWindow(self, len(self.fileStorage),
                                                 text = "controlled")

        # initialization
        controls = self.controlFrame.controlsGet() # selected controls
        self.controlReport.clear()  # clears report
        self.controlReport.addControls(controls) # adds selected controls to ControlReport

        self.problemOccured = False
        # processing      
        for file in self.fileStorage:
            tag = "x" if file in self.fileStorage.tagged else " "
            try:
                if file in self.fileStorage.pairedfiles:
                    cm = CM(file, nameR = self.fileStorage.pairedfiles[file])
                else:
                    cm = CM(file, nameR = "auto")
            except Exception:
                self.problemOccured = True
                for control in controls:
                    self.controlReport.addFile((control[0], [file, "Failed to load!", "Problem",
                                                             9999999, tag]))
            else:
                for control in controls:
                    try:
                        assessment = self.assessImportance(cm = cm, control = control, file = file)
                        assessment[1].append(tag)
                    except Exception:
                        self.problemOccured = True
                        assessment = (control[0], [file, "Failed to compute!", "Problem",
                                                   9999998, tag])
                    self.controlReport.addFile(assessment)
                     
            if len(self.fileStorage) > 1:
                if self.stoppedProcessing:
                    return
                else:
                    self.progressWindow.addOne()
                    
        self.controlReport.updateTree()

        # progressbar and status
        if len(self.fileStorage) > 1:
            self.progressWindow.destroy()
            if self.problemOccured:
                self.status.set("Files were not processed successfully!")
                self.bell()
            else:
                self.status.set("Files were processed successfully.")
        else:
            if self.problemOccured:
                self.status.set("File was not processed successfully!")
                self.bell()
            else:
                self.status.set("File was processed successfully.")          
        

    def assessImportance(self, cm, control, file):
        "method needed for evaluation of importance of results from CM class' control methods"
        method = control[0]
        startTime, time = int(self.timeFrame.startTimeVar.get()), int(self.timeFrame.timeVar.get())
        results = eval("cm.{}".format(control[1]))
        description = ""
        importance = ""
        value = 0
        
        if method == "Reflections":
            if results[1] * 3 + results[0] > 5:
                importance = "Problem"
            elif results[1] * 3 + results[0] > 2:
                importance = "Warning"
            elif results[0] > 0:
                importance = "Concern"
            else:
                importance = "OK"
            if results[1] != 1:
                description = "{} points problematic, {} of concern".format(results[1], results[0])
            else:
                description = "{} point problematic, {} of concern".format(results[1], results[0])
            value = results[1]

            self.fileStorage.saveReflections(file = file, points = results[2] + results[3])
            
        elif method == "Outside Points":
            if results > 250:
                importance = "Problem"
            elif results > 50:
                importance = "Warning"
            elif results > 5:
                importance = "Concern"
            else:
                importance = "OK"
            if results != 1:
                description = "{} points outside of arena".format(results)
            else:
                description = "1 point outside of arena"
            value = results

        elif method == "Bad Points":
            if results > 10:
                importance = "Problem"
            elif results > 5:
                importance = "Warning"
            elif results > 2:
                importance = "Concern"
            else:
                importance = "OK"
            description = "{0:.2f}% bad points".format(results)
            value = results            
                    
        return (method, [cm.nameA, description, importance, value])

            
    def saveFun(self):
        "writes results from controlReport to selected file"
        output = self.saveToFrame.saveToVar.get()
        if not self.controlReport.files:
            self.bell()
            self.status.set("No results prepared for saving.")
            return
        if not output:
            self.bell()
            self.status.set("You have to select a name of a file.")
            return
        
        separator = optionGet("ResultSeparator", ",", "str")
        results = separator.join(["File"] + self.controlReport.controls)
        for file in self.controlReport.files:
            filename = returnName(filename = file, allFiles = self.controlReport.files)
            result = [filename]
            for control in self.controlReport.controls:
                result += [i[3] for i in self.controlReport.results[control] if i[0] == file]
            results += "\n" + separator.join(map(str, result))
     
        writeResults(output, results)
        self.status.set("Results were saved.")
        

    def checkProcessing(self):
        "method updating page after change of notebook tab"
        self.controlReport.clear(clearAll = False)
        self.controlReport.updateTree()
        
        if self.fileStorage.arenafiles:
            self.process.state(["!disabled"])
        else:
            self.process.state(["disabled"])

        if self.fileStorage.arenafiles or self.fileStorage.wrongfiles:
            self.fileStorageFrame.removeFiles.state(["!disabled"])
        else:
            self.fileStorageFrame.removeFiles.state(["disabled"])

        self.fileStorageFrame.chosenVar.set(len(self.fileStorage))
        self.fileStorageFrame.nonMatchingVar.set(len(self.fileStorage.wrongfiles))
コード例 #22
0
ファイル: processor.py プロジェクト: bahniks/CM_Manager_0_3_4
class Processor(ttk.Frame):
    "represents 'Process' page in the main window notebook"
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (10, 10, 12, 12)
        self.root = root # potreba pouze pro progressbar


        # variables    
        self.status = StringVar()
              
        # frames
        self.parametersF = ParameterFrame(self)
        self.fileStorageFrame= FileStorageFrame(self)
        self.saveToFrame = SaveToFrame(self, parent = "processor")
        self.timeFrame = TimeFrame(self)
        self.optionFrame = OptionFrame(self, text = "Options")
        
        # buttons
        self.process = ttk.Button(self, text = "Process Files", command = self.processFun,
                                  state = "disabled")

        # labels
        self.statusBar = ttk.Label(self, textvariable = self.status)

        
        # adding to grid
        self.parametersF.grid(column = 0, row = 3, columnspan = 4, sticky = (N, W), padx = 4)
        self.fileStorageFrame.grid(column = 3, row = 0, pady = 5, padx = 4)
        self.timeFrame.grid(column = 1, row = 5, padx = 30, pady = 15, sticky = (N, W))
        
        self.process.grid(column = 3, row = 7, sticky = (S, E), padx = 4, pady = 3)

        self.statusBar.grid(column = 0, row = 7, columnspan = 3, sticky = (N, S, E, W), padx = 6,
                            pady = 3)
       
        self.saveToFrame.grid(column = 1, row = 1, columnspan = 3, sticky = (N, S, E, W),
                              padx = 6, pady = 2)

        self.optionFrame.grid(column = 0, row = 5, sticky = (N, E), padx = 6)
  

        # what should be enlarged
        self.columnconfigure(2, weight = 1)
        self.rowconfigure(2, weight = 3)
        self.rowconfigure(4, weight = 2)
        self.rowconfigure(6, weight = 2)


    def processCheck(self):
        "checks whether all inputs are valid - helper function for processFun"

        if self.saveToFrame.saveToVar.get() == "":
            raise Exception("You have to choose an output file!")
        
        if len(self.root.fileStorage.arenafiles) == 0:
            raise Exception("You haven't chosen any file!")

        try:
            startTime = float(self.timeFrame.startTimeVar.get())
        except Exception:
            raise Exception("Start time has to be a number!")
        try:
            time = float(self.timeFrame.timeVar.get())
        except Exception:
            raise Exception("Stop time has to be a number!")
        
        if startTime >= time:
            raise Exception("Start time must be smaller than stop time!")

        if time < 0 or startTime < 0:
            raise Exception("Time has to be set to a positive value")

        if not os.path.exists(os.path.split(self.saveToFrame.saveToVar.get())[0]):
            if os.path.split(self.saveToFrame.saveToVar.get())[0]:
                raise Exception("Pathname of the output file doesn't exist!")
      
        
    def processFun(self):
        "processes chosen files and saves the results in the save-to file"
        # checking for mistakes
        try:
            self.processCheck()
        except Exception as e:
            self.bell()
            self.status.set(e)
            return                   

        # files to be processed
        self.filesToProcess = [file for file in self.root.fileStorage.arenafiles if \
                               self.optionFrame.processFile(file)]

        # progressWindow and check for number of files for processing
        if len(self.filesToProcess) > 1:
            self.stoppedProcessing = False
            self.progressWindow = ProgressWindow(self, len(self.filesToProcess))
        elif len(self.filesToProcess) == 0:
            self.bell()
            self.status.set("There is no file selected for processing!")
            return

        # selected methods          
        methods = []
        for method in Parameters().parameters:
            if eval("self.parametersF.%sVar.get()" % (method[0].replace(" ", ""))):
                methods.append(method[0])
           
        output = self.saveToFrame.saveToVar.get()
        startTime = float(self.timeFrame.startTimeVar.get())
        time = float(self.timeFrame.timeVar.get())
        separator = optionGet("ResultSeparator", ",", "str")
        
        results = separator.join(["File"] + methods)
        
        if self.optionFrame.saveTags.get():
            results += separator + "Tags"

        self.log = Log(methods, startTime, time, self.filesToProcess, self.root.fileStorage,
                       self.optionFrame.removeReflectionsWhere.get(), output)
        self.someProblem = False

        developer = optionGet("Developer", False, 'bool')
        
        for file in self.filesToProcess:
            # loading of cm object
            if methods:
                try:
                    if file in self.root.fileStorage.pairedfiles:
                        cm = CM(file, nameR = self.root.fileStorage.pairedfiles[file])
                    else:
                        cm = CM(file, nameR = "auto")

                    if self.optionFrame.removeReflections(file):
                        cm.removeReflections(points = self.root.fileStorage.reflections.get(file,
                                                                                            None))
                except Exception as e:
                    if developer:
                        print(e)   
                    filename = returnName(filename = file, allFiles =
                                          self.root.fileStorage.arenafiles) 
                    results += "\n" + filename + "{}NA".format(separator) * len(methods)
                    self.log.failedToLoad.append(file)
                    self.someProblem = True
                    continue
                    
            
            result = []
            for method in Parameters().parameters:
                if method[0] in methods:
                    try:
                        if method[2] == "custom":
                            exec("from Stuff.Parameters import {}".format(method[5]))
                        result.append(eval(method[1]))
                    except Exception as e:
                        if developer:
                            print(e)   
                        result.append("NA")
                        self.log.methodProblems[method[0]].append(file)
                        self.someProblem = True


            result = separator.join(map(str, result))
            if methods:
                result = separator + result               
            filename = returnName(filename = file, allFiles = self.root.fileStorage.arenafiles)      
            results += "\n" + filename + result
            
            if self.optionFrame.saveTags.get(): # tag inclusion in results
                if file in self.root.fileStorage.tagged:
                    results += separator + "1"
                else:
                    results += separator + "0"
            
            if len(self.filesToProcess) > 1:
                if self.stoppedProcessing:
                    writeResults(output, results)
                    self.log.stopped = file
                    self.log.writeLog()
                    self.status.set("Processing stopped")
                    return
                else:
                    self.progressWindow.addOne()


        writeResults(output, results)
        self.log.writeLog()

        # change of status bar and closing of progressWindow
        if len(self.filesToProcess) > 1:
            if self.someProblem:
                self.status.set("Files were processed.")
            else:
                self.status.set("Files were processed successfully.")
            self.progressWindow.destroy()
        else:
            if self.someProblem:
                self.status.set("File was processed.")
            else:
                self.status.set("File was processed successfully.")

        # removal of files from fileStorage if selected
        if self.optionFrame.clearFilesAfterProcessing.get():
            for file in self.filesToProcess:
                self.root.fileStorage.arenafiles.remove(file)
            self.fileStorageFrame.chosenVar.set(len(self.root.fileStorage.arenafiles))
            if not self.root.fileStorage.arenafiles:
                self.fileStorageFrame.removeFiles.state(["disabled"]) 
                self.process.state(["disabled"])

        if self.someProblem:
            ProcessingProblemDialog(self, self.log.filename)


    def checkProcessing(self):
        "method updating page after change of notebook tab"
        if self.root.fileStorage.arenafiles and self.saveToFrame.saveToVar.get():
            self.process.state(["!disabled"])
        else:
            self.process.state(["disabled"])

        if self.root.fileStorage.arenafiles or self.root.fileStorage.wrongfiles:
            self.fileStorageFrame.removeFiles.state(["!disabled"])
        else:
            self.fileStorageFrame.removeFiles.state(["disabled"])        

        self.fileStorageFrame.chosenVar.set(len(self.root.fileStorage.arenafiles))
        self.fileStorageFrame.nonMatchingVar.set(len(self.root.fileStorage.wrongfiles))
コード例 #23
0
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (7, 7, 9, 9)

        self.root = root
        self.fileStorage = self.root.fileStorage

        # file selection
        self.saveToVar = StringVar()
        self.saveToVar.set(True)
        self.fileStorageFrame = FileStorageFrame(self)
        self.fileStorageFrame.grid(column = 1, row = 0, columnspan = 2, sticky = (N, S, E, W),
                                   pady = 5, padx = 2)

        # statusbar
        self.status = StringVar()
        
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.statusBar.grid(column = 0, row = 4, columnspan = 2, sticky = (S, E, W))
        
        # control button
        self.process = ttk.Button(self, text = "Control", command = self.controlFun)
        self.process.grid(column = 2, row = 4, sticky = E)
        self.process.state(["disabled"])
        
        # report
        self.reportFrame = ttk.LabelFrame(self, text = "Report")
        self.reportFrame.grid(column = 0, row = 0, rowspan = 4, sticky = (N, S, E, W), padx = 5)
        self.reportFrame.columnconfigure(0, weight = 1)
        self.reportFrame.rowconfigure(0, weight = 1)

        self.upFrame = ttk.Frame(self.reportFrame)
        self.upFrame.grid(column = 0, row = 0, columnspan = 2, sticky = (N, S, E, W))
        self.upFrame.columnconfigure(0, weight = 1)
        self.upFrame.rowconfigure(0, weight = 1)
        
        self.contentTree = ttk.Treeview(self.upFrame, selectmode = "none")
        self.contentTree.grid(column = 0, row = 0, sticky = (N, S, E, W))
        self.contentTree["columns"] = ("description", "importance", "tag")
        self.contentTree.column("#0", width = 250, anchor = "w")
        self.contentTree.heading("#0", text = "Problem",
                                 command = lambda: self.orderReport("name"))
        self.contentTree.column("description", width = 200, anchor = "e")
        self.contentTree.heading("description", text = "Description",
                                 command = lambda: self.orderReport("description"))
        self.contentTree.column("importance", width = 60, anchor = "e")
        self.contentTree.heading("importance", text = "Importance",
                                 command = lambda: self.orderReport("importance"))
        self.contentTree.column("tag", width = 10, anchor = "center")
        self.contentTree.heading("tag", text = "Tag", command = lambda: self.orderReport("tag"))
        self.scrollbar = ttk.Scrollbar(self.upFrame, orient = VERTICAL,
                                       command = self.contentTree.yview)
        self.scrollbar.grid(column = 1, row = 0, sticky = (N, S, E))
        self.contentTree.configure(yscrollcommand = self.scrollbar.set)
        
        self.saveToFrame = SaveToFrame(self.reportFrame, label = False)
        self.saveToFrame.grid(column = 0, row = 1, sticky = (E, W))

        self.saveBut = ttk.Button(self.reportFrame, text = "Save", command = self.saveFun)
        self.saveBut.grid(column = 1, row = 1, sticky = E, padx = 2)
    
        self.controlReport = ControlReport(self)
                       
        self.contentTree.tag_bind("file", "<Double-1>", lambda e: self.treeDoubleClick(e))
        self.contentTree.tag_bind("file", "<3>", lambda e: self.filePopUp(e))
        self.contentTree.tag_bind("ok", "<3>", lambda e: self.okPopUp(e))
        self.contentTree.tag_bind("control", "<3>", lambda e: self.controlPopUp(e))
        self.contentTree.tag_configure("comment", background = commentColor())
        
        # method selection frame                
        self.controlFrame = ControlFrame(self)
        self.controlFrame.grid(column = 1, row = 1, columnspan = 2, sticky = (N, W), padx = 10,
                               pady = 55)

        # time frame
        self.timeFrame = TimeFrame(self)
        self.timeFrame.grid(column = 1, row = 2, columnspan = 2, sticky = (N, W), padx = 10)


        self.columnconfigure(0, weight = 1)
        self.rowconfigure(2, weight = 1)
コード例 #24
0
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (7, 7, 9, 9)

        self.root = root
        self.fileStorage = self.root.fileStorage

        # file selection
        self.saveToVar = StringVar()
        self.saveToVar.set(True)
        self.fileStorageFrame = FileStorageFrame(self)
        self.fileStorageFrame.grid(column = 1, row = 0, columnspan = 2, sticky = (N, S, E, W),
                                   pady = 5, padx = 2)

        # statusbar
        self.status = StringVar()
        
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.statusBar.grid(column = 0, row = 4, columnspan = 2, sticky = (S, E, W))
        
        # control button
        self.process = ttk.Button(self, text = "Control", command = self.controlFun)
        self.process.grid(column = 2, row = 4, sticky = E)
        self.process.state(["disabled"])
        
        # report
        self.reportFrame = ttk.LabelFrame(self, text = "Report")
        self.reportFrame.grid(column = 0, row = 0, rowspan = 4, sticky = (N, S, E, W), padx = 5)
        self.reportFrame.columnconfigure(0, weight = 1)
        self.reportFrame.rowconfigure(0, weight = 1)

        self.upFrame = ttk.Frame(self.reportFrame)
        self.upFrame.grid(column = 0, row = 0, columnspan = 2, sticky = (N, S, E, W))
        self.upFrame.columnconfigure(0, weight = 1)
        self.upFrame.rowconfigure(0, weight = 1)
        
        self.contentTree = ttk.Treeview(self.upFrame, selectmode = "none")
        self.contentTree.grid(column = 0, row = 0, sticky = (N, S, E, W))
        self.contentTree["columns"] = ("description", "importance")
        self.contentTree.column("#0", width = 250, anchor = "w")
        self.contentTree.heading("#0", text = "Problem",
                                 command = self.orderReportByNames)
        self.contentTree.column("description", width = 200, anchor = "e")
        self.contentTree.heading("description", text = "Description",
                                 command = self.orderReportByResults)
        self.contentTree.column("importance", width = 60, anchor = "e")
        self.contentTree.heading("importance", text = "Importance",
                                 command = self.orderReportByImportance)      
        self.scrollbar = ttk.Scrollbar(self.upFrame, orient = VERTICAL,
                                       command = self.contentTree.yview)
        self.scrollbar.grid(column = 1, row = 0, sticky = (N, S, E))
        self.contentTree.configure(yscrollcommand = self.scrollbar.set)
        
        self.saveToFrame = SaveToFrame(self.reportFrame, label = False)
        self.saveToFrame.grid(column = 0, row = 1, sticky = (E, W))

        self.saveBut = ttk.Button(self.reportFrame, text = "Save", command = self.saveFun)
        self.saveBut.grid(column = 1, row = 1, sticky = E, padx = 2)
    
        self.controlReport = ControlReport() #!
                       
        self.contentTree.tag_bind("file", "<Double-1>", lambda e: self.treeDoubleClick(e))
        
        # method selection frame                
        self.controlFrame = ControlFrame(self)
        self.controlFrame.grid(column = 1, row = 1, columnspan = 2, sticky = (N, W), padx = 10,
                               pady = 55)


        # time frame
        self.timeFrame = TimeFrame(self)
        self.timeFrame.grid(column = 1, row = 2, columnspan = 2, sticky = (N, W), padx = 10)


        self.columnconfigure(0, weight = 1)
        self.rowconfigure(2, weight = 1)
コード例 #25
0
class Controller(ttk.Frame):
    "represents 'Control' page in the main window notebook"
    def __init__(self, root):
        super().__init__(root)

        self["padding"] = (7, 7, 9, 9)

        self.root = root
        self.fileStorage = self.root.fileStorage

        # file selection
        self.saveToVar = StringVar()
        self.saveToVar.set(True)
        self.fileStorageFrame = FileStorageFrame(self)
        self.fileStorageFrame.grid(column = 1, row = 0, columnspan = 2, sticky = (N, S, E, W),
                                   pady = 5, padx = 2)

        # statusbar
        self.status = StringVar()
        
        self.statusBar = ttk.Label(self, textvariable = self.status)
        self.statusBar.grid(column = 0, row = 4, columnspan = 2, sticky = (S, E, W))
        
        # control button
        self.process = ttk.Button(self, text = "Control", command = self.controlFun)
        self.process.grid(column = 2, row = 4, sticky = E)
        self.process.state(["disabled"])
        
        # report
        self.reportFrame = ttk.LabelFrame(self, text = "Report")
        self.reportFrame.grid(column = 0, row = 0, rowspan = 4, sticky = (N, S, E, W), padx = 5)
        self.reportFrame.columnconfigure(0, weight = 1)
        self.reportFrame.rowconfigure(0, weight = 1)

        self.upFrame = ttk.Frame(self.reportFrame)
        self.upFrame.grid(column = 0, row = 0, columnspan = 2, sticky = (N, S, E, W))
        self.upFrame.columnconfigure(0, weight = 1)
        self.upFrame.rowconfigure(0, weight = 1)
        
        self.contentTree = ttk.Treeview(self.upFrame, selectmode = "none")
        self.contentTree.grid(column = 0, row = 0, sticky = (N, S, E, W))
        self.contentTree["columns"] = ("description", "importance")
        self.contentTree.column("#0", width = 250, anchor = "w")
        self.contentTree.heading("#0", text = "Problem",
                                 command = self.orderReportByNames)
        self.contentTree.column("description", width = 200, anchor = "e")
        self.contentTree.heading("description", text = "Description",
                                 command = self.orderReportByResults)
        self.contentTree.column("importance", width = 60, anchor = "e")
        self.contentTree.heading("importance", text = "Importance",
                                 command = self.orderReportByImportance)      
        self.scrollbar = ttk.Scrollbar(self.upFrame, orient = VERTICAL,
                                       command = self.contentTree.yview)
        self.scrollbar.grid(column = 1, row = 0, sticky = (N, S, E))
        self.contentTree.configure(yscrollcommand = self.scrollbar.set)
        
        self.saveToFrame = SaveToFrame(self.reportFrame, label = False)
        self.saveToFrame.grid(column = 0, row = 1, sticky = (E, W))

        self.saveBut = ttk.Button(self.reportFrame, text = "Save", command = self.saveFun)
        self.saveBut.grid(column = 1, row = 1, sticky = E, padx = 2)
    
        self.controlReport = ControlReport() #!
                       
        self.contentTree.tag_bind("file", "<Double-1>", lambda e: self.treeDoubleClick(e))
        
        # method selection frame                
        self.controlFrame = ControlFrame(self)
        self.controlFrame.grid(column = 1, row = 1, columnspan = 2, sticky = (N, W), padx = 10,
                               pady = 55)


        # time frame
        self.timeFrame = TimeFrame(self)
        self.timeFrame.grid(column = 1, row = 2, columnspan = 2, sticky = (N, W), padx = 10)


        self.columnconfigure(0, weight = 1)
        self.rowconfigure(2, weight = 1)


    def orderReportByNames(self):
        opened = {}
        for child in self.contentTree.get_children():
            opened[child] = self.contentTree.item(child, "open")
            self.contentTree.delete(child)
        self.controlReport.orderedBy = "name"
        self.controlReport.updateTree(self, deleteExisting = True)
        for child in self.contentTree.get_children():
            if child in opened:
                self.contentTree.item(child, open=opened[child])

    def orderReportByResults(self):
        opened = {}
        for child in self.contentTree.get_children():
            opened[child] = self.contentTree.item(child, "open")
            self.contentTree.delete(child)
        self.controlReport.orderedBy = "description"
        self.controlReport.updateTree(self, deleteExisting = True)
        for child in self.contentTree.get_children():
            if child in opened:
                self.contentTree.item(child, open=opened[child])

    def orderReportByImportance(self):
        opened = {}
        for child in self.contentTree.get_children():
            opened[child] = self.contentTree.item(child, "open")
            self.contentTree.delete(child)
        self.controlReport.orderedBy = "importance"
        self.controlReport.updateTree(self, deleteExisting = True)        
        for child in self.contentTree.get_children():
            if child in opened:
                self.contentTree.item(child, open=opened[child])
                
        
    def treeDoubleClick(self, event):
        "shows tracks in a ShowTracks toplevel window"
        item = self.contentTree.identify("item", event.x, event.y)
        name = item.rstrip("0123456789")
        tracks = self.controlReport.files # <- zmenit aby zobrazovalo serazene
        if item:
            time = (self.timeFrame.startTimeVar.get(), self.timeFrame.timeVar.get())
            showTracks = ShowTracks(self, nameA = name, tracks = tracks, time = time,
                                    controlled = True)


    def controlFun(self):
        "processes selected files, clears report, shows results in a report"

        # progressbar
        if len(self.root.fileStorage.arenafiles) > 1:
            self.stoppedProcessing = False
            self.progressWindow = ProgressWindow(self, len(self.root.fileStorage.arenafiles),
                                                 text = "controlled")

        # initialization
        controls = self.controlFrame.controlsGet() # selected controls
        self.controlReport.clear(self)  # clears report
        self.controlReport.addControls(controls) # adds selected controls to ControlReport

        self.problemOccured = False
        # processing      
        for file in self.root.fileStorage.arenafiles:
            try:
                if file in self.root.fileStorage.pairedfiles:
                    cm = CM(file, nameR = self.root.fileStorage.pairedfiles[file])
                else:
                    cm = CM(file, nameR = "auto")
            except Exception:
                self.problemOccured = True
                for control in controls:
                    self.controlReport.addFile((control[0], (file, "Failed to load!", "Problem",
                                                             9999999)))
            else:
                for control in controls:
                    try:
                        assessment = self.assessImportance(cm = cm, control = control, file = file)
                    except Exception:
                        self.problemOccured = True
                        assessment = (control[0], (file, "Failed to compute!", "Problem",
                                                   9999998))
                    self.controlReport.addFile(assessment)
                     
            if len(self.root.fileStorage.arenafiles) > 1:
                if self.stoppedProcessing:
                    return
                else:
                    self.progressWindow.addOne()
                    
        self.controlReport.updateTree(self)

        # progressbar and status
        if len(self.root.fileStorage.arenafiles) > 1:
            self.progressWindow.destroy()
            if self.problemOccured:
                self.status.set("Files were not processed successfully!")
                self.bell()
            else:
                self.status.set("Files were processed successfully.")
        else:
            if self.problemOccured:
                self.status.set("File was not processed successfully!")
                self.bell()
            else:
                self.status.set("File was processed successfully.")          
        

    def assessImportance(self, cm, control, file):
        "method needed for evaluation of importance of results from CM class' control methods"
        method = control[0]
        results = eval("cm.{}()".format(control[1]))
        description = ""
        importance = ""
        value = 0
        
        if method == "Reflections":
            if results[1] * 3 + results[0] > 5:
                importance = "Problem"
            elif results[1] * 3 + results[0] > 2:
                importance = "Warning"
            elif results[0] > 0:
                importance = "Concern"
            else:
                importance = "OK"
            if results[1] != 1:
                description = "{} points problematic, {} of concern".format(results[1], results[0])
            else:
                description = "{} point problematic, {} of concern".format(results[1], results[0])
            value = results[1]

            self.root.fileStorage.saveReflections(file = file, points = results[2] + results[3])
            
        elif method == "Outside Points":
            if results > 250:
                importance = "Problem"
            elif results > 50:
                importance = "Warning"
            elif results > 5:
                importance = "Concern"
            else:
                importance = "OK"
            if results != 1:
                description = "{} points outside of arena".format(results)
            else:
                description = "1 point outside of arena"
            value = results

        elif method == "Bad Points":
            if results > 10:
                importance = "Problem"
            elif results > 5:
                importance = "Warning"
            elif results > 2:
                importance = "Concern"
            else:
                importance = "OK"
            description = "{0:.2f}% bad points".format(results)
            value = results            
                    
        return (method, (cm.nameA, description, importance, value))

            
    def saveFun(self):
        "writes results from controlReport to selected file"
        output = self.saveToFrame.saveToVar.get()
        if not self.controlReport.files:
            self.bell()
            self.status.set("No results prepared for saving.")
            return
        if not output:
            self.bell()
            self.status.set("You have to select a name of a file.")
            return
        
        separator = optionGet("ResultSeparator", ",", "str")
        results = separator.join(["File"] + self.controlReport.controls)
        for file in self.controlReport.files:
            filename = returnName(filename = file, allFiles = self.controlReport.files)
            result = [filename]
            for control in self.controlReport.controls:
                result += [i[3] for i in self.controlReport.results[control] if i[0] == file]
            results += "\n" + separator.join(map(str, result))
     
        writeResults(output, results)
        self.status.set("Results were saved.")
        

    def checkProcessing(self):
        "method updating page after change of notebook tab"        
        if self.root.fileStorage.arenafiles:
            self.process.state(["!disabled"])
        else:
            self.process.state(["disabled"])

        if self.root.fileStorage.arenafiles or self.root.fileStorage.wrongfiles:
            self.fileStorageFrame.removeFiles.state(["!disabled"])
        else:
            self.fileStorageFrame.removeFiles.state(["disabled"])

        self.fileStorageFrame.chosenVar.set(len(self.root.fileStorage.arenafiles))
        self.fileStorageFrame.nonMatchingVar.set(len(self.root.fileStorage.wrongfiles))
コード例 #26
0
ファイル: options.py プロジェクト: bahniks/CM_Manager_0_3_4
class OptionsCM(Toplevel):
    "options window reachable from menu"
    def __init__(self, root):
        super().__init__(root)
        self.title("Options")
        self.grab_set()
        self.focus_set()
        self.resizable(FALSE, FALSE)
        placeWindow(self, 824, 844)
        self["padx"] = 10
        self["pady"] = 10
        
        self.parametersF = ParameterFrame(self, "Default parameters")

        # default filetype of processor output
        self.fileTypeVar = StringVar()
        self.fileTypeVar.set(optionGet("DefProcessOutputFileType", ".txt", "str"))

        self.fileTypeFrame = ttk.Labelframe(self, text = "Default output filetype")

        self.txtRadioBut = ttk.Radiobutton(self.fileTypeFrame, text = ".txt",
                                           variable = self.fileTypeVar, value = ".txt")
        self.csvRadioBut = ttk.Radiobutton(self.fileTypeFrame, text = ".csv",
                                           variable = self.fileTypeVar, value = ".csv")
        
        self.txtRadioBut.grid(row = 1, column = 0, padx = 2, pady = 2, sticky = W)
        self.csvRadioBut.grid(row = 0, column = 0, padx = 2, pady = 2, sticky = W)

        # output separator
        self.separatorVar = StringVar()
        self.separatorVar.set(optionGet("ResultSeparator", ",", "str"))

        self.separatorFrame = ttk.Labelframe(self, text = "Result separator")

        self.commaRadioBut = ttk.Radiobutton(self.separatorFrame, text = "Comma",
                                             variable = self.separatorVar, value = ",")
        self.semicolonRadioBut = ttk.Radiobutton(self.separatorFrame, text = "Semicolon",
                                                 variable = self.separatorVar, value = ";")        
        self.tabRadioBut = ttk.Radiobutton(self.separatorFrame, text = "Tab",
                                           variable = self.separatorVar, value = "\t")
        
        self.commaRadioBut.grid(row = 0, padx = 2, pady = 2, sticky = W)
        self.semicolonRadioBut.grid(row = 1, padx = 2, pady = 2, sticky = W)
        self.tabRadioBut.grid(row = 2, padx = 2, pady = 2, sticky = W)

        # save filename as full path
        self.saveFilenameAs = RadioFrame(self, text = "Save (show) filename as:",
                                         optionName = "SaveFullPath", default = "Basename",
                                         options = ["Basename", "Full path", "Unique path"])

        # selection of directories
        self.directoriesFrame = ttk.Frame(self)
        self.directoriesFrame.columnconfigure(0, weight = 1)
        self.directoryOptions = [
            ("Default directory for file selection", "FileDirectory", os.getcwd()),
            ("Default directory for results", "ResultDirectory", os.getcwd()),
            ("Directory for saving of processing logs", "LogDirectory",
             os.path.join(os.getcwd(), "Stuff", "Logs")),
            ("Directory for images", "ImageDirectory", os.getcwd()),
            ("Directory for saving of selected files", "SelectedFilesDirectory",
             os.path.join(os.getcwd(), "Stuff", "Selected files"))]
        for count, option in enumerate(self.directoryOptions):
            exec("""self.{1} = ChooseDirectoryFrame(self.directoriesFrame, '{0}', '{1}', \
                 r'{2}')""".format(*option))
            exec("self.{}.grid(row = {}, column = 0, pady = 2, padx = 2, sticky = (E, W))".format(
                option[1], count))

        # default time
        self.timeLabFrame = ttk.Labelframe(self, text = "Default time")
        self.timeFrame = TimeFrame(self.timeLabFrame)
        self.timeFrame.grid(row = 0, column = 0)

        # processor options
        self.processorOptions = OptionFrame(self, text = "Default process options")

        # checking messages
        self.messageCheckingFrame = ttk.Labelframe(self, text = "Messages and new versions")
        self.messageCheckingVar = BooleanVar()
        self.messageCheckingVar.set(optionGet("CheckMessages", True, "bool"))
        self.messageCheckingChB = ttk.Checkbutton(self.messageCheckingFrame,
                                                  variable = self.messageCheckingVar,
                                                  onvalue = True, offvalue = False,
                                                  text = "Check messages and new versions")
        self.messageCheckingChB.grid(column = 0, row = 0)
        
        # buttons
        self.buttonFrame = ttk.Frame(self)
        self.buttonFrame.columnconfigure(1, weight = 1)

        self.saveBut = ttk.Button(self.buttonFrame, text = "Save", command = self.saveFun)
        self.okBut = ttk.Button(self.buttonFrame, text = "Ok", command = self.okFun)
        self.cancelBut = ttk.Button(self.buttonFrame, text = "Cancel", command = self.cancelFun)

        self.saveBut.grid(column = 0, row = 0, padx = 3, pady = 2, sticky = (W))
        self.okBut.grid(column = 1, row = 0, padx = 3, pady = 2)
        self.cancelBut.grid(column = 2, row = 0, padx = 3, pady = 2, sticky = (E))

        # grid of self contents        
        self.parametersF.grid(row = 0, column = 0, columnspan = 4, sticky = (N, W), padx = 4,
                              pady = 2)
        self.fileTypeFrame.grid(row = 2, column = 0, columnspan = 2, padx = 3, pady = 4,
                                sticky = (W, N, E, S))
        self.buttonFrame.grid(row = 8, column = 0, columnspan = 4, padx = 3, pady = 4,\
                              sticky = (E, W, N, S))
        self.separatorFrame.grid(row = 3, column = 0, columnspan = 2, padx = 3, pady = 4,
                                 sticky = (W, N, E))
        self.saveFilenameAs.grid(row = 2, column = 2, padx = 3, pady = 4, sticky = (N, W, E))
        self.directoriesFrame.grid(row = 5, column = 0, columnspan = 5, padx = 3, pady = 8,
                                   sticky = (N, W, E))
        self.timeLabFrame.grid(row = 2, column = 3, padx = 3, pady = 4, sticky = (N, W))
        self.processorOptions.grid(row = 3, column = 2, pady = 4, padx = 4, sticky = (N, W),
                                   columnspan = 2, rowspan = 2)
        self.messageCheckingFrame.grid(row = 4, column = 0, columnspan = 2, sticky = (N, W),
                                       pady = 3, padx = 3)
                                   
        
    def saveFun(self):
        "saves all options"
        for parameter in Parameters().parameters:
            optionWrite(parameter[4], bool(eval(("self.parametersF." +\
                                                 parameter[0].replace(" ", "") + "Var.get()"
                                                 ))))
        optionWrite("DefProcessOutputFileType", "'" + self.fileTypeVar.get() + "'")
        optionWrite("SaveFullPath", self.saveFilenameAs.get())
        optionWrite("ResultSeparator", "'" + self.separatorVar.get() + "'")
        optionWrite("DefStartTime", self.timeFrame.startTimeVar.get())
        optionWrite("DefStopTime", self.timeFrame.timeVar.get())
        optionWrite("ProcessWhat", "'" + self.processorOptions.processWhat.get() + "'")
        optionWrite("RemoveReflectionsWhere",
                    "'" + self.processorOptions.removeReflectionsWhere.get() + "'")
        optionWrite("DefSaveTags", self.processorOptions.saveTags.get())
        optionWrite("DefClearFilesAfterProcessing",
                    self.processorOptions.clearFilesAfterProcessing.get())
        optionWrite("CheckMessages", bool(self.messageCheckingVar.get()))
        for option in self.directoryOptions:
            directory = eval("self.{}.get()".format(option[1])).rstrip("\/")
            if os.path.exists(directory):
                optionWrite(option[1], "r'" + directory  + "'")
            else:
                messagebox.showinfo(message = "Directory " + directory + " does not exist.",
                                    icon = "error", parent = self, title = "Error",
                                    detail = "Choose an existing directory.")
                return False
        return True
                

    def okFun(self):
        "saves options and exits"
        if self.saveFun():
            self.destroy()


    def cancelFun(self):
        "destroys the window"
        self.destroy()     
コード例 #27
0
    def __init__(self, root, files, time = "auto", controlled = False):
        super().__init__(root)

        self.rowconfigure(0, weight = 1)

        self.allFiles = files # used when un-selecting files
        self.files = files # currently diplayed files
        self.controlled = controlled # True if FileTree called from controller
        self.root = root
        self.fileStorage = self.root.fileStorage
        self.index = self.root.index # which file is selected when the FileTree is initialized
        self.usedProblemOrder = -1 # by which method is the tree ordered (index)
        if time == "auto":
            time = (0, 20)

        # tree
        self.treeFrame = ttk.Frame(self)
        self.treeFrame.grid(column = 0, row = 0, columnspan = 3, sticky = (N, S, E, W))
        self.treeFrame.rowconfigure(0, weight = 1)
        self.treeFrame.columnconfigure(0, weight = 1)
        
        self.tree = ttk.Treeview(self.treeFrame, selectmode = "browse", height = 20)
        self.tree.grid(column = 0, row = 0, sticky = (N, S, E, W))
        
        if self.controlled:
            columns = ("problem", "tag")
        else:
            columns = ("tag")
        self.tree["columns"] = columns

        self.tree.column("#0", width = 240, anchor = "w")        
        self.tree.heading("#0", text = "File", command = self.orderByNames)

        self.tree.column("tag", width = 40, anchor = "center")
        self.tree.heading("tag", text = "Tag", command = self.orderByTag)
        
        if self.controlled:
            self.tree.column("problem", width = 160, anchor = "e")
            self.tree.heading("problem", text = "Problems", command = self.orderByProblem)
            
        self.scrollbar = ttk.Scrollbar(self.treeFrame, orient = VERTICAL,
                                       command = self.tree.yview)
        self.scrollbar.grid(column = 1, row = 0, sticky = (N, S, E))
        self.tree.configure(yscrollcommand = self.scrollbar.set)

        self.tree.bind("<1>", lambda e: self.click(e))
        self.tree.bind("<3>", lambda e: self.popUp(e))

        self.drawTree()

        # bottom frame
        self.bottomFrame = ttk.Frame(self)
        self.bottomFrame.grid(column = 0, row = 1, columnspan = 2)
        self.bottomFrame.columnconfigure(3, weight = 1)
        self.bottomFrame.rowconfigure(1, weight = 1)

        # previous and next buttons
        self.fileLabFrame = ttk.Labelframe(self.bottomFrame, text = "File")
        self.fileLabFrame.grid(column = 0, row = 0, sticky = (N, W), pady = 3, padx = 1)
        
        self.previousBut = ttk.Button(self.fileLabFrame, text = "Previous",
                                      command = self.previousFun)
        self.previousBut.grid(column = 0, row = 0, padx = 3)
        
        self.nextBut = ttk.Button(self.fileLabFrame, text = "Next", command = self.nextFun)
        self.nextBut.grid(column = 1, row = 0, padx = 3)

        # tag buttons
        self.tagLabFrame = ttk.Labelframe(self.bottomFrame, text = "Tagging")
        self.tagLabFrame.grid(column = 0, row = 1, sticky = (N, W), rowspan = 2,
                              padx = 1, pady = 4)
        
        self.tagBut = ttk.Button(self.tagLabFrame, text = "Tag file", command = self.tagFun)
        self.tagBut.grid(column = 1, row = 1, padx = 3)
        self.checkTag()

        self.tagAllBut = ttk.Button(self.tagLabFrame, text = "Tag all", command = self.tagAllFun)
        self.tagAllBut.grid(column = 2, row = 1, padx = 3)

        self.untagAllBut = ttk.Button(self.tagLabFrame, text = "Remove all tags",
                                      command = self.untagAllFun)
        self.untagAllBut.grid(column = 3, row = 1, padx = 3)

        # time frame
        self.timeLabFrame = ttk.Labelframe(self.bottomFrame, text = "Time")
        self.timeLabFrame.grid(column = 3, row = 0, rowspan = 2, sticky = N, pady = 3)
        self.timeLabFrame.root = self.root
        
        self.timeFrame = TimeFrame(self.timeLabFrame, onChange = True)
        self.timeFrame.grid(column = 0, row = 0)
        self.timeFrame.timeVar.set(time[1])
        self.timeFrame.startTimeVar.set(time[0])

        # remove reflections checkbutton
        self.removeReflectionsVar = BooleanVar()
        self.removeReflectionsVar.set(False)
        self.removeReflections = ttk.Checkbutton(self.bottomFrame, text = "Remove reflections",
                                                 variable = self.removeReflectionsVar,
                                                 command = self.toggleReflections)
        self.removeReflections.grid(column = 2, row = 2, padx = 7, pady = 5, sticky = (N, W),
                                    columnspan = 2)

        # frame radiobuttons       
        self.frameFrame = ttk.Labelframe(self.bottomFrame, text = "Frame")
        self.frameFrame.grid(column = 2, row = 0, padx = 5, rowspan = 2, pady = 3, sticky = N)

        self.frameVar = StringVar()
        self.frameVar.set("arena")
        
        self.arenaFrameRB = ttk.Radiobutton(self.frameFrame, text = "Arena",
                                            variable = self.frameVar, value = "arena",
                                            command = self.toggleFrame)
        self.arenaFrameRB.grid(column = 0, row = 0, pady = 2)
        
        self.roomFrameRB = ttk.Radiobutton(self.frameFrame, text = "Room",
                                           variable = self.frameVar, value = "room",
                                           command = self.toggleFrame)
        self.roomFrameRB.grid(column = 0, row = 1, pady = 2)
コード例 #28
0
class OptionsCM(Toplevel):
    "options window reachable from menu"
    def __init__(self, root):
        super().__init__(root)
        self.root = root
        self.title(m.fullname[m.mode] + " options")
        self.grab_set()
        self.focus_set()
        self.resizable(FALSE, FALSE)
        placeWindow(self, 720, 350)
        self["padx"] = 10
        self["pady"] = 10
        
        self.parametersF = ParameterFrame(self, "Default parameters")

        # selection of directories
        self.fileDirectory = ChooseDirectoryFrame(self, "Default directory for file selection",
                                                  "FileDirectory", r'{}'.format(os.getcwd()),
                                                  False)

        # default time
        self.timeLabFrame = ttk.Labelframe(self, text = "Default time")
        self.timeFrame = TimeFrame(self.timeLabFrame, observe = False, loadtime = False)
        self.timeFrame.grid(row = 0, column = 0)
    
        # buttons
        self._createButtons()

        # grid of self contents        
        self.parametersF.grid(row = 0, column = 0, columnspan = 2, sticky = (N, W), padx = 4,
                              pady = 2)
        self.buttonFrame.grid(row = 3, column = 0, columnspan = 2, padx = 3, pady = 6,
                              sticky = (E, W, N, S))
        self.timeLabFrame.grid(row = 1, column = 1, padx = 6, pady = 4, sticky = (N, W, E))
        self.fileDirectory.grid(row = 1, column = 0, pady = 2, padx = 2, sticky = (E, W))
        
                                   
    def _createButtons(self):
        # buttons
        self.buttonFrame = ttk.Frame(self)
        self.buttonFrame.columnconfigure(0, weight = 3)
        self.buttonFrame.columnconfigure(2, weight = 1)
        self.buttonFrame.columnconfigure(4, weight = 3)

        self.okBut = ttk.Button(self.buttonFrame, text = "Ok", command = self.okFun)
        self.cancelBut = ttk.Button(self.buttonFrame, text = "Cancel", command = self.cancelFun)

        self.okBut.grid(column = 1, row = 0, padx = 3, pady = 2)
        self.cancelBut.grid(column = 3, row = 0, padx = 3, pady = 2, sticky = (E))

        
    def saveFun(self):
        "saves all options"
        self.parametersF.saveSelectedParametersAsDefault()
        optionWrite("DefStartTime", self.timeFrame.startTimeVar.get(), False)
        optionWrite("DefStopTime", self.timeFrame.timeVar.get(), False)
        directory = self.fileDirectory.get().rstrip("\/")
        if os.path.exists(directory):
            optionWrite("FileDirectory", "r'" + directory  + "'", False)
        else:
            messagebox.showinfo(message = "Directory " + directory + " does not exist.",
                                icon = "error", parent = self, title = "Error",
                                detail = "Choose an existing directory.")
            return False
        return True


    def okFun(self):
        "saves options and exits"
        if self.saveFun():
            self.destroy()


    def cancelFun(self):
        "destroys the window"
        self.destroy()