Example #1
0
    def getView(self, window):
        view = Frame(window)
        Label(view, text=self.question).pack()
        if (self.screentype == "Scale"):
            var = DoubleVar()
            slider = Scale(view,
                           from_=0,
                           to=100,
                           orient=HORIZONTAL,
                           variable=var,
                           command=self.updateButtonText)
            slider.pack()
            self.btn = Button(
                master=view,
                text="Your Answer = " + str(slider.get()),
                command=lambda *args: self.check(str(slider.get()), view))
            self.btn.pack()
        elif (self.screentype == "Radio"):
            var = StringVar()

            Radiobutton(
                view,
                text=self.answers[0],
                value="A",
                variable=var,
                command=lambda *args: self.check(var.get(), view)).pack()
            Radiobutton(
                view,
                text=self.answers[1],
                value="B",
                variable=var,
                command=lambda *args: self.check(var.get(), view)).pack()
            Radiobutton(
                view,
                text=self.answers[2],
                value="C",
                variable=var,
                command=lambda *args: self.check(var.get(), view)).pack()
            Radiobutton(
                view,
                text=self.answers[3],
                value="D",
                variable=var,
                command=lambda *args: self.check(var.get(), view)).pack()
            var.set(None)

        else:
            Button(view,
                   text=self.answers[0],
                   command=lambda *args: self.check("A", view)).pack()
            Button(view,
                   text=self.answers[1],
                   command=lambda *args: self.check("B", view)).pack()
            Button(view,
                   text=self.answers[2],
                   command=lambda *args: self.check("C", view)).pack()
            Button(view,
                   text=self.answers[3],
                   command=lambda *args: self.check("D", view)).pack()
        return view
Example #2
0
class StatusFrame(Frame):
    def __init__(self, root):
        super().__init__(root, padding=10)
        self.var_stat = StringVar()
        self.var_stat.set("Ready")
        self.lbl_stat = Label(self, textvariable=self.var_stat)
        self.lbl_stat.pack(anchor=W)

        self.var_statmin = StringVar()
        self.var_statmin.set("|> ")
        self.lbl_statmin = Label(self, textvariable=self.var_statmin)
        self.lbl_statmin.pack(anchor=W)

        self.var_prog = DoubleVar()
        self.var_prog.set(0)
        self.prog_stat = Progressbar(self, maximum=100, variable=self.var_prog)
        self.prog_stat.pack(fill=X, anchor=W)

    def set_minor(self, message):
        self.var_statmin.set(message)

    def set_major(self, message):
        self.var_stat.set(message)

    def set_progress(self, progress):
        self.var_prog.set(progress)
Example #3
0
class TScaleObj:
    needDrawingUpdate = True
    def __init__(self,cellx,celly,window,title,defaultValue):
        self.InitEntry(defaultValue)
        #Label init
        self.label = Label(window, text=title)
        self.label.grid(column=cellx,row=celly, sticky = "W" )
        #Entry init
        self.entry = Entry(window,textvariable=self.EntryValue)
        self.entry.grid(column=cellx,row=celly+1, sticky = "W" )
        #Buttons init
        self.buttSub = Button(window,text = "Sub" ,command= self.Sub,image = image_minus)
        self.buttSub.grid(column=cellx+3,row=celly+1, sticky = "W")
        self.buttAdd = Button(window,text = "Add",command=self.Add,image = image_plus )
        self.buttAdd.grid(column=cellx+2,row=celly+1, sticky = "W")
        self.buttValidate = Button(window,text = "<-",command=self.setNewEntry,image = image_valid )
        self.buttValidate.grid(column=cellx+1,row=celly+1, sticky = "W")

    def UpdateValidEntry(self,value):
        self.lastValidEntry = value
        self.RefreshDisplayedValue()
        self.needDrawingUpdate = True

    def setNewEntry(self):
        newValue = self.EntryValue.get()

        if(self.CheckForValidEntry(newValue)):
            self.UpdateValidEntry(float(newValue))
        else :
            self.RefreshDisplayedValue()

    def CheckForValidEntry(self,value):
        try:
            v = float(value)
            if v <0:
                floatable = False
            else : 
                floatable = True
        except:
            floatable = False
        return floatable
            
    def RefreshDisplayedValue(self):
        self.EntryValue.set(self.lastValidEntry)

    def IncrementEntryValue(self,inc):
        newValue = self.lastValidEntry + inc
        if self.CheckForValidEntry(newValue):
            self.UpdateValidEntry(newValue)

    def Add(self):
        self.IncrementEntryValue(0.001)
    def Sub(self):
        self.IncrementEntryValue(-0.001)

    def InitEntry (self,defaultValue):
        self.EntryValue = DoubleVar()
        self.EntryValue.set(defaultValue)
        self.lastValidEntry = defaultValue
Example #4
0
def handle_common_properties(widgets):
    color = [None]

    def on_choose_color():
        color[0] = askcolor()[1]

    widgets["color_btn"]["command"] = on_choose_color
    marker = StringVar()
    widgets["marker_lent"].entry["textvariable"] = marker
    alpha = DoubleVar()
    alpha.set(1.0)
    widgets["alpha_scale"].scale["variable"] = alpha
    return color, marker, alpha
Example #5
0
    def add_vectors(self):
        self.clear()
        num_vectors = DoubleVar()
        dimension = DoubleVar()
        num_vectors.set(2)
        dimension.set(2)

        num_vectors_entry = Entry(mainframe,
                                  width=5,
                                  textvariable=num_vectors,
                                  font=MATRIX_FONT)
        num_vectors_entry.grid(column=1, row=2, sticky=W)
        dimension_entry = Entry(mainframe,
                                width=5,
                                textvariable=dimension,
                                font=MATRIX_FONT)
        dimension_entry.grid(column=1, row=3, sticky=W)

        num_vectors_label = Label(mainframe, text="vectors", font=LABEL_FONT)
        num_vectors_label.grid(column=2, row=2, sticky=E)
        dimension_label = Label(mainframe, text="dimensions", font=LABEL_FONT)
        dimension_label.grid(column=2, row=3, sticky=E)

        def add_vectors_input():
            try:
                num_vectors_value = num_vectors.get()
                dimension_value = dimension.get()
                if 2 <= num_vectors_value <= 15 and 2 <= dimension_value <= 15 and num_vectors_value % 1 == 0 and dimension_value % 1 == 0:
                    self.vectors_input(int(num_vectors_value),
                                       int(dimension_value), ADD_VECTORS)
                else:
                    raise ValueError
            except ValueError:
                messagebox.showerror(
                    "Error",
                    "Number of vectors or dimensions must be between 2 and 15")
            except TclError:
                messagebox.showerror("Error", "Invalid input")
                return

        submit = Button(mainframe,
                        text="Submit",
                        command=add_vectors_input,
                        font=LABEL_FONT)
        submit.grid(column=1, row=4, columnspan=2, sticky=W)
        dimension_header = Label(
            mainframe,
            text="Enter the number of vectors to add and their dimensions:",
            font=LABEL_FONT)
        dimension_header.grid(column=1, row=1, columnspan=FILL, sticky=W)
Example #6
0
    def initUI(self):
        """Initialize the User Interface"""
        global var
        columns = [0, 1, 2, 3, 4]  # columns grid padding
        rows = [0, 1, 2, 3, 4, 5]  # rows grid padding
        var = StringVar()
        self.master.title("Speed-Reader")

        Style().configure("Tbutton", padding=(0, 5, 0, 5), font="serif 10")
        self.columnconfigure(columns, pad=5, minsize=25)
        self.rowconfigure(rows, pad=5, minsize=25)

        self.textLabel = Label(self, textvariable=var)

        self.textLabel.grid(row=0, column=2)

        self.restart = Button(self,
                              text="Restart Text",
                              command=self.restart_txt)
        self.restart.grid(row=1, column=2)

        self.pause = Button(self, text="PLAY/PAUSE", command=self.pause_txt)
        self.pause.grid(row=2, column=2)

        init_slide_val = DoubleVar()  # create initial slider value variable
        self.speed_slider = Scale(
            self,
            cursor='sb_h_double_arrow',
            from_=100,
            to=300,
            length=200,
            tickinterval=50,
            resolution=50,
            orient='horizontal',
            variable=init_slide_val,
            command=lambda x: self.change_speed(self.speed_slider.get()))

        init_slide_val.set(200)  # initialize the slider to 200 WPM
        self.speed_slider.grid(row=3, column=2)

        self.quit = Button(self, text="QUIT", command=self.master.destroy)
        self.quit.grid(row=4, column=2)

        self.addFile = Button(self, text="OPEN", command=self.UploadAction)
        self.addFile.grid(row=5, column=2)

        self.textLabel.after(1000, self.display_text)

        self.pack()
Example #7
0
    def rref(self):
        self.clear()
        rows = DoubleVar()
        columns = DoubleVar()
        rows.set(2)
        columns.set(2)

        row_entry = Entry(mainframe,
                          width=5,
                          textvariable=rows,
                          font=MATRIX_FONT)
        row_entry.grid(column=1, row=2, sticky=W)
        column_entry = Entry(mainframe,
                             width=5,
                             textvariable=columns,
                             font=MATRIX_FONT)
        column_entry.grid(column=1, row=3, sticky=W)

        row_label = Label(mainframe, text="rows", font=LABEL_FONT)
        row_label.grid(column=2, row=2, sticky=E)
        column_label = Label(mainframe, text="columns", font=LABEL_FONT)
        column_label.grid(column=2, row=3, sticky=E)

        def rref_input():
            try:
                row_value = rows.get()
                column_value = columns.get()
                if 2 <= row_value <= 15 and 2 <= column_value <= 15 and row_value % 1 == 0 and column_value % 1 == 0:
                    self.matrix_input(int(row_value), int(column_value), RREF)
                else:
                    raise ValueError
            except ValueError:
                messagebox.showerror("Error",
                                     "Matrix must be between 2x2 and 15x15")
            except TclError:
                messagebox.showerror("Error", "Invalid input")
                return

        submit = Button(mainframe,
                        text="Submit",
                        command=rref_input,
                        font=LABEL_FONT)
        submit.grid(column=1, row=4, columnspan=2, sticky=W)
        dimension_header = Label(
            mainframe,
            text="Enter the dimensions of the matrix (2x2 - 15x15):",
            font=LABEL_FONT)
        dimension_header.grid(column=1, row=1, columnspan=4, sticky=W)
Example #8
0
    def systems(self):
        self.clear()
        var = DoubleVar()
        eq = DoubleVar()
        var.set(2)
        eq.set(2)

        var_entry = Entry(mainframe,
                          width=5,
                          textvariable=var,
                          font=MATRIX_FONT)
        var_entry.grid(column=1, row=2, sticky=W)
        eq_entry = Entry(mainframe, width=5, textvariable=eq, font=MATRIX_FONT)
        eq_entry.grid(column=1, row=3, sticky=W)

        var_label = Label(mainframe, text="variables (2-10)", font=LABEL_FONT)
        var_label.grid(column=2, row=2, sticky=E)
        eq_label = Label(mainframe, text="equations (2-10)", font=LABEL_FONT)
        eq_label.grid(column=2, row=3, sticky=E)

        def systems_input():
            try:
                var_value = var.get()
                eq_value = eq.get()
                if 2 <= var_value <= 10 and 2 <= eq_value <= 10 and var_value % 1 == 0 and eq_value % 1 == 0:
                    self.matrix_input(int(eq_value),
                                      int(var_value) + 1, SYSTEMS)
                else:
                    raise ValueError
            except ValueError:
                messagebox.showerror(
                    "Error",
                    "Number of variables or equations must be between 2 and 10"
                )
            except TclError:
                messagebox.showerror("Error", "Invalid input")
                return

        submit = Button(mainframe,
                        text="Submit",
                        command=systems_input,
                        font=LABEL_FONT)
        submit.grid(column=1, row=4, columnspan=2, sticky=W)
        dimension_header = Label(
            mainframe,
            text="Enter the number of variables and equations:",
            font=LABEL_FONT)
        dimension_header.grid(column=1, row=1, columnspan=4, sticky=W)
Example #9
0
class Progress(Progressbar):
    def __init__(self, master=None, box=None, autoplay=True, **kw):
        super().__init__(master=master, **kw)
        self.box = box
        self.time = DoubleVar(master=master, value=0)
        self.timestr = StringVar(master=master, value='Current MP3:')
        self.current_mp3id_str = StringVar(master=master, value='')
        self.pb = Progressbar(master=master, variable=self.time)
        # self.pb['value'] = self.time.get()
        # self.pb['maximum'] = self.length.get()
        self.label = Label(master=master, textvariable=self.timestr, text='Current MP3:')
        self.label.pack()
        self.current_mp3id = Label(master, textvariable=self.current_mp3id_str)
        self.current_mp3id.pack()
        self.pb.pack()
        # self.started = False
        self.update(autoplay=autoplay)
    
    # def update_loop(self, autoplay=True):
    #     while True:
    #         self.update()

    def update(self, autoplay=True):
        if not self.box.started:
            pass
        else:
            mp3id = self.box.current_mp3id
            time = self.box.mp3.get_time()/1000
            length = self.box.mp3.get_length()/1000
            timestr = f'{time:.2f} / {length:.2f}'
            self.time.set(time)
            self.timestr.set(timestr)
            self.current_mp3id_str.set(f'Current MP3: {mp3id}')
            # self.length.set(self.box.mp3.get_length())
            self.pb['maximum'] = length
            if self.box.mp3.get_state()==State.Ended:
                self.timestr.set(f'{length:.2f} / {length:.2f}')
                if autoplay:
                    self.box.next()
                    self.box.play()
            # print('update ',timestr)
            try:
                print(self.mp3)
            except:
                pass
            # self.length = self.box.mp3.get_length()
        self.after(100, func=self.update)
Example #10
0
    def make_form(self):
        form = Frame(self, relief='raised', border=2)
        left = Frame(form)
        right = Frame(form)
        form.pack(fill='both')
        left.pack(side='left')
        right.pack(side='right', expand='yes', fill='both')

        for feature in feature_names:
            lab = Label(left, width=15, text=feature + ':')
            ent = Entry(right)
            lab.pack(side='top')
            ent.pack(side='top', pady=.5, expand='yes', fill='both')
            var = DoubleVar()
            ent.config(textvariable=var)
            var.set('0.0')
            self.measurements.append(var)
Example #11
0
    def update_variables(self):
        new_variable_array = []
        new_lvw_array = []
        for i in np.arange(0, int(self.number_of_variables.get()), 1):
            x_label = tk.Label(root)
            ft = tkFont.Font(family='Times', size=15)
            x_label["font"] = ft
            x_label["fg"] = "#000"
            x_label["justify"] = "center"
            x_label["text"] = "x" + str(i + 1)
            x_label.grid(row=3, column=i + 1)

            x_val_var = DoubleVar(root)
            if (i < len(self.variables)):
                x_val_var.set(self.variables[i].value.get())
            x_value_entry = tk.Entry(root, textvariable=x_val_var)
            x_value_entry["borderwidth"] = "1px"
            ft = tkFont.Font(family='Times', size=10)
            x_value_entry["font"] = ft
            x_value_entry["fg"] = "#333333"
            x_value_entry["justify"] = "center"
            x_value_entry.grid(row=4, column=i + 1)

            x_w_var = DoubleVar(root)
            if (i < len(self.variables)):
                x_w_var.set(self.variables[i].weight.get())
            x_weight_entry = tk.Entry(root, textvariable=x_w_var)
            x_weight_entry["borderwidth"] = "1px"
            ft = tkFont.Font(family='Times', size=10)
            x_weight_entry["font"] = ft
            x_weight_entry["fg"] = "#333333"
            x_weight_entry["justify"] = "center"
            x_weight_entry.grid(row=5, column=i + 1)

            new_variable_array.append(Item(i, x_val_var, x_w_var))
            new_lvw_array.append((x_label, x_value_entry, x_weight_entry))

        self.variables = new_variable_array
        self.lvw = new_lvw_array
        return 0
Example #12
0
    def create_buttons(self, parent, create_sliders):

        self.jso = Button(parent,
                          text="Import from .json",
                          command=self.import_json)
        self.jso.grid(row=0, column=0, sticky="w")
        self.sav = Button(parent,
                          text="Import from .sav",
                          command=self.import_sav)
        self.sav.grid(row=0, column=1, sticky="w")

        self.scales = []

        # create sliders
        if create_sliders:
            self.jso.grid_configure(row=0, column=0)
            self.sav.grid_configure(row=1, column=0)
            resources = [
                'minerals', 'energy', 'physics', 'society', 'engineering'
            ]
            colors = ["red", "yellow", "blue", "green", "orange"]
            for i in range(len(resources)):
                var = DoubleVar()
                var.set(500)
                callback = lambda event, tag=i: self.weight_update(event, tag)
                b = Scale(parent,
                          from_=1,
                          to=1000,
                          variable=var,
                          length=135,
                          orient='horizontal',
                          troughcolor=colors[i],
                          resolution=1,
                          label=resources[i],
                          showvalue=0)
                b.grid(row=2 + i, column=0, sticky="w")
                b.bind('<ButtonRelease-1>',
                       self.redraw)  # redraw when user release scale
                self.scales.append(var)
Example #13
0
    def dot_product(self):
        self.clear()
        dimension = DoubleVar()
        dimension.set(2)

        dimension_entry = Entry(mainframe,
                                width=5,
                                textvariable=dimension,
                                font=MATRIX_FONT)
        dimension_entry.grid(column=1, row=2, sticky=W)

        dimension_label = Label(mainframe, text="dimensions", font=LABEL_FONT)
        dimension_label.grid(column=2, row=2, sticky=E)

        def dot_product_input():
            try:
                dimension_value = dimension.get()
                if 2 <= dimension_value <= 15 and dimension_value % 1 == 0:
                    self.vectors_input(2, int(dimension_value), DOT_PRODUCT)
                else:
                    raise ValueError
            except ValueError:
                messagebox.showerror(
                    "Error", "Number of dimensions must be between 2 and 15")
            except TclError:
                messagebox.showerror("Error", "Invalid input")
                return

        submit = Button(mainframe,
                        text="Submit",
                        command=dot_product_input,
                        font=LABEL_FONT)
        submit.grid(column=1, row=4, columnspan=FILL, sticky=W)
        dimension_header = Label(
            mainframe,
            text="Enter the number of dimensions for the vectors:",
            font=LABEL_FONT)
        dimension_header.grid(column=1, row=1, columnspan=FILL, sticky=W)
Example #14
0
class Parameter:
    def __init__(self, name, var):
        self.name = name
        self.var = var
        self.val = float(var.get())
        self.doublevar = DoubleVar(value=self.val)

    def getVal(self):
        try:
            val = float(self.var.get())
            if val == 0 and cantBeZero(self.name):
                return self.doublevar.get()
            self.doublevar.set(val)
            return val
        except ValueError:
            return self.doublevar.get()

    def udv(self, *args):
        self.setVal(self.doublevar.get())

    def setVal(self, value):
        self.var.set(value)
        self.doublevar.set(value)
Example #15
0
class App:
    def __init__(self, master):
        self.initDone = False
        self.initGuiData()
        self.master = master
        self.master.title("Hot wire cutter (version 0.1.f)")
        self.nb = ttk.Notebook(self.master)
        self.nb.enable_traversal()
        self.queueTkSendMsg = queue.Queue()
        self._thread_cmd = threading.Thread(target=self.execCmd,
                                            args=(self.queueTkSendMsg, "rien"))
        self._thread_cmd.setDaemon(
            True
        )  #added by mstrens in order to kill automatically the thread when program close
        self._thread_cmd.start()

        self.queueTkGetMsg = queue.Queue()
        self.tGrbl = Grbl(
            self.nb, self, self.queueTkGetMsg
        )  #create an instance of Gerbil in order to communicate with GRBL
        # queue is used to get message back from interface

        self.tProfil = Profil(self.nb,
                              self)  #add a tab for selecting the profile
        self.tTransform = Transform(self.nb,
                                    self)  #add a tab to modify the profile
        self.tBloc = Bloc(self.nb,
                          self)  #add a tab to design the wing and the bloc
        self.tMargin = Margin(self.nb,
                              self)  #add a tab to design the vertical margin
        self.tMaterial = Material(self.nb,
                                  self)  #add a tab to specify the material
        self.tGuillotine = Guillotine(
            self.nb, self, self.queueTkSendMsg)  #add a tab to make guillotine
        self.tCut = Cut(self.nb, self)  #add a tab to cut
        self.tTable = Table(self.nb,
                            self)  #add a tab to define the Table (size)
        self.nb.pack()
        atexit.register(self.tGrbl.disconnectToGrbl)
        self.initDone = True
        self.running = True

        self.periodicCall()
        self.validateAllOn = True
        self.validateAll(0)  #validate all

        #self.tBloc.toTableRight.set(self.tTable.dY.get() - self.tTable.lG.get() - self.tTable.lD.get() - self.tBloc.toTableLeft.get() - self.tBloc.lX.get() )
        #print (self.tBloc.toTableRight.get())

    def execCmd(self, queue, rien):
        """
        thread in order to execute task outside the main tkhtread (when they can take to much time e.g.)
        get Cmd via a queue queueTkSendMsg
        used e.g. when a button is clicked in Thinker
        not sure it is really requested for this application
        """
        while True:
            msg = queue.get()
            if msg == "Connect":
                self.tGrbl.connectToGrbl()
                self.tGuillotine.updateBtnState()
            elif msg == "Disconnect":
                self.tGrbl.disconnectToGrbl()
                self.tGuillotine.updateBtnState()

    def processIncoming(self):
        """Handle all messages currently in the queue, if any."""
        while self.queueTkGetMsg.qsize():
            try:
                msg = self.queueTkGetMsg.get(0) + "\n"
                # Check contents of message and do whatever is needed. As a
                # simple test, print it (in real life, you would
                # suitably update the GUI's display in a richer fashion).
                #print("getting a message in queue",msg)
                self.tGuillotine.msgBox.insert(END, msg)
            except queue.Empty:
                # just on general principles, although we don't
                # expect this branch to be taken in this case
                pass

    def periodicCall(self):
        """
        Check every 200 ms if there is something new in the queue.
        execute it when tkinter is sleeping
        """
        self.processIncoming()
        if not self.running:
            # This is the brutal stop of the system. You may want to do
            # some cleanup before actually shutting it down.
            #import sys
            #sys.exit(1)
            pass
        self.master.after(200, self.periodicCall)

    #def calback(self, a , b, c):
    #    print("do something")

    def initGuiData(self):
        #not saved with config
        self.validateAllOn = False
        self.warningMsg = StringVar(value="")
        self.cutMsg = StringVar(value="")
        self.limMinX = DoubleVar(
            value='0.0')  # min value to plot on X axis (not saved in .ini)
        self.limMinY = DoubleVar(
            value='0.0')  # min value to plot on Y axis (not saved in .ini)
        self.zoom = StringVar(value="1X")
        #self.zoom.trace('w', self.calback)
        self.configUploadFileName = None
        self.tableUploadFileName = None
        self.tableSaveFileName = None
        self.materialUploadFileName = None
        self.materialSaveFileName = None
        self.connected = StringVar(value="OFF")
        self.grblStatus = StringVar(value="Not connected")
        self.grblXG = DoubleVar(value="0")  #grbl horizontal left pos
        self.grblYG = DoubleVar(value="0")  #grbl vertical left pos
        self.grblXD = DoubleVar(value="0")  #grbl horizontal right pos
        self.grblYD = DoubleVar(value="0")  #grbl vertical right pos
        self.grblF = DoubleVar(value="0")  #grbl feed rate
        self.grblS = DoubleVar(value="0")  #grbl heating
        self.gMoveAxis = StringVar(
            value="Both")  # grbl axis to move (left,right)
        self.gMoveDist = DoubleVar(value="10")  #grbl mistance to move
        # Transformed profil based on original (filled by validateTransform) ; is an numpy array and not a usual List
        #take care of Chord, but not of position of block and margins...
        self.tRootX = np.array([])
        self.tRootY = np.array([])
        self.tRootS = []
        self.tTipX = np.array([])
        self.tTipY = np.array([])
        self.tTipS = []
        # Position profil (in a numpy array) based on "t" profile and position of block and margins...
        self.pRootX = np.array([])
        self.pRootY = np.array([])
        self.pRootS = []
        self.pTipX = np.array([])
        self.pTipY = np.array([])
        self.pTipS = []
        #guillotine
        self.gVSpeedNoCut = DoubleVar(value='5')
        self.gHSpeedNoCut = DoubleVar(value='5')
        self.gCuttingSpeed = DoubleVar(value='5')
        self.gApplyCalculatedHeating = IntVar(value='1')
        self.gHeating = DoubleVar(value='50')
        self.gType = StringVar(value="Vertical")
        self.gCuttingWhile = StringVar(value="Both")
        #self.gHeatWhileArming = IntVar(value='1')
        self.gVDist = DoubleVar(value='10')
        self.gHDist = DoubleVar(value='10')

        #saved in config
        #profil
        self.oRootX = [
        ]  # original profil : usual python List ; saved in the files
        self.oRootY = []
        self.oRootS = []  # synchro points
        self.oTipX = []
        self.oTipY = []
        self.oTipS = []
        self.nameRoot = StringVar(value="")
        self.nameTip = StringVar(value="")
        #transform
        self.cRoot = DoubleVar(value='200.0')  #chord
        self.cTip = DoubleVar(value='150.0')  #chord
        self.incidenceRoot = DoubleVar(value='0.0')
        self.thicknessRoot = DoubleVar(value='100.0')
        self.vInvertRoot = IntVar(value='0')
        self.incidenceTip = DoubleVar(value='0.0')
        self.thicknessTip = DoubleVar(value='100.0')
        self.vInvertTip = IntVar(value='0')
        self.covering = DoubleVar(value='0.0')
        self.keepChord = IntVar(value='0')
        self.smooth = IntVar(value='0')
        self.nbrPoints = IntVar(value='50')
        self.repartition = DoubleVar(value='2.0')
        self.reducePoints = IntVar(value='0')

        #bloc
        self.blocLX = DoubleVar(value='600.0')  #Length = envergure
        self.blocHZ = DoubleVar(value='50.0')  #height of the bloc
        self.fLeading = DoubleVar(value='10.0')  #fleche
        self.fTrailing = DoubleVar(
            value='-30'
        )  #self.cRoot.get() - self.cTip.get() - self.fLeading.get()) #calculated
        self.mLeading = DoubleVar(value='5.0')
        self.mTrailingRoot = DoubleVar(value='10.0')
        self.mTrailingTip = DoubleVar(value='10.0')
        self.leftRightWing = StringVar(value='Left')
        self.blocPosition = StringVar(value='Left')  #Left or Right position
        self.blocToTableLeft = DoubleVar(
            value='100.0')  #calculated but depend on bloc position
        self.blocToTableRight = DoubleVar(
            value='10.0')  #calculated but depend on bloc position
        self.blocToTableTrailingRoot = IntVar(value='50')
        self.blocToTableTrailingTip = IntVar(value='50')  #calculated
        self.blocToTableLeadingRoot = IntVar(value='50')  #calculated
        self.blocToTableLeadingTip = IntVar(value='50')  #calculated
        #margin
        self.hTrailingRoot = DoubleVar(value='10.0')
        self.hTrailingTip = DoubleVar(value='10.0')  #calculated
        self.hLeadingRoot = DoubleVar(value='10.0')  #calculated
        self.hLeadingTip = DoubleVar(value='10.0')  #calculated
        self.hMaxRoot = DoubleVar(value='10.0')  #calculated
        self.hMaxTip = DoubleVar(value='10.0')  #calculated
        self.hMinRoot = DoubleVar(value='10.0')  #calculated
        self.hMinTip = DoubleVar(value='10.0')  #calculated
        self.hOffset = DoubleVar(value='10.0')  #heigh of the base of the bloc
        self.alignProfil = StringVar(value="Trailing")
        self.hProfil = DoubleVar(
            value='20.0')  #heigh of the profile in the bloc
        self.angleInRoot = DoubleVar(value='0.0')
        self.angleInTip = DoubleVar(value='0.0')
        self.angleOutRoot = DoubleVar(value='0.0')
        self.angleOutTip = DoubleVar(value='0.0')
        """
        self.hMaxRootNorm = 0
        self.hMinRootNorm = 0
        self.hLeadingRootNorm = 0
        self.hMaxTipNorm = 0
        self.hMinTipNorm = 0
        self.hLeadingTipNorm = 0
        """
        #Material
        self.mSpeedHigh = DoubleVar(value='10.0')  #speed max
        self.mSpeedHalf = DoubleVar(value='5.0')  #speed min
        self.mSpeedLow = DoubleVar(value='1.0')  #speed min
        self.mRadSpHigh = DoubleVar(value='0.9')  #Radiance at high max
        self.mRadSpHalf = DoubleVar(value='1.5')  #Radiance at half speed
        self.mHeatSpHigh = IntVar(value='90')  #Heat at High speed
        self.mHeatSpLow = IntVar(value='40')  #Heat at low speed
        self.mName = StringVar(value="No material name")
        #table
        self.tableYY = DoubleVar(value='1000.0')  # distance between 2 axis
        self.tableYG = DoubleVar(
            value='20.0')  #distance between left Y axis and left table edge
        self.tableYD = DoubleVar(value='20.0')  # same on the rigth side
        self.cMaxY = DoubleVar(value='500.0')  # max course in Y
        self.cMaxZ = DoubleVar(value='200.0')  # max course in Z (height)
        self.vMaxY = DoubleVar(value='10.0')  # max speed in Y
        self.vMaxZ = DoubleVar(value='5.0')  # max speed in Z (height)
        self.tHeatingMax = DoubleVar(value='100.0')  # max heating
        self.tName = StringVar(value="No table name")
        #self.tComPort = StringVar(value="Select a Com port")
        self.tComPort = StringVar(value="COM6")
        self.tBaudrate = StringVar(value="115200")
        self.tPreHeat = DoubleVar(value='5.0')  # delay between Heat and move
        self.tPostHeat = DoubleVar(value='5.0')  # delay between Move and Heat

        #cut
        self.vCut = DoubleVar(
            value='2.0'
        )  # max speed for cutting (on root or tip depending the longest)
        self.gCodeStart1 = StringVar(value="")
        self.gCodeStart2 = StringVar(value="")
        self.gCodeStart3 = StringVar(value="")
        self.gCodeStart4 = StringVar(value="")
        self.gCodeEnd1 = StringVar(value="")
        self.gCodeEnd2 = StringVar(value="")
        self.gCodeEnd3 = StringVar(value="")
        self.gCodeEnd4 = StringVar(value="")
        self.gCodeLetters = StringVar(value="XYZA")

        #self.validatePart()

    def uploadConfig(self):
        #global configUploadFileName
        #configUploadFileName = filedialog.askopenfilename(initialdir="C:/Data/",
        self.configUploadFileName = filedialog.askopenfilename(\
                            filetypes =(("Ini files", "*.ini"),("All files","*.*")),
                            title = "Choose a file."
                            )
        if len(self.configUploadFileName) > 0:
            self.validateAllOn = False
            #config.read('config.ini')
            config = configparser.ConfigParser()
            config.add_section("Profil")
            config.add_section("Transform")
            config.add_section("Bloc")
            config.add_section("Material")
            config.add_section("Table")
            config.add_section("Cut")
            config.add_section("Guillotine")

            config.read(self.configUploadFileName)
            self.oRootX = stringToListOfFloat(config.get("Profil", "RootX"))
            self.oRootY = stringToListOfFloat(config.get("Profil", "RootY"))
            self.oRootS = stringToListOfFloat(config.get("Profil", "RootS"))
            self.oTipX = stringToListOfFloat(config.get("Profil", "TipX"))
            self.oTipY = stringToListOfFloat(config.get("Profil", "TipY"))
            self.oTipS = stringToListOfFloat(config.get("Profil", "TipS"))
            self.nameRoot.set(value=config.get("Profil", "nameRoot"))
            self.nameTip.set(value=config.get("Profil", "nameTip"))

            self.cRoot.set(value=config.getfloat("Transform", "cRoot"))
            self.cTip.set(value=config.getfloat("Transform", "cTip"))
            self.incidenceRoot.set(
                value=config.getfloat("Transform", "incidenceRoot"))
            self.thicknessRoot.set(
                value=config.getfloat("Transform", "thicknessRoot"))
            self.vInvertRoot.set(
                value=config.getint("Transform", "vInvertRoot"))
            self.incidenceTip.set(
                value=config.getfloat("Transform", "incidenceTip"))
            self.thicknessTip.set(
                value=config.getfloat("Transform", "thicknessTip"))
            self.vInvertTip.set(value=config.getint("Transform", "vInvertTip"))
            self.covering.set(value=config.getfloat("Transform", "covering"))
            self.keepChord.set(value=config.getint("Transform", "keepChord"))
            self.smooth.set(value=config.getint("Transform", "smooth"))
            self.nbrPoints.set(value=config.getint("Transform", "nbrPoints"))
            self.repartition.set(
                value=config.getfloat("Transform", "repartition"))
            self.reducePoints.set(
                value=config.getint("Transform", "reducePoints"))

            self.blocLX.set(value=config.getfloat("Bloc", "blocLX"))
            self.blocHZ.set(value=config.getfloat("Bloc", "blocHZ"))
            self.fLeading.set(value=config.getfloat("Bloc", "fLeading"))
            self.mLeading.set(value=config.getfloat("Bloc", "mLeading"))
            self.mTrailingRoot.set(
                value=config.getfloat("Bloc", "mTrailingRoot"))
            self.mTrailingTip.set(
                value=config.getfloat("Bloc", "mTrailingTip"))
            self.leftRightWing.set(value=config.get("Bloc", "leftRightWing"))
            self.blocPosition.set(value=config.get("Bloc", "blocPosition"))
            self.blocToTableLeft.set(
                value=config.getfloat("Bloc", "blocToTableLeft"))
            self.blocToTableRight.set(
                value=config.getfloat("Bloc", "blocToTableRight"))
            self.blocToTableTrailingRoot.set(
                value=config.getint("Bloc", "blocToTableTrailingRoot"))
            self.blocToTableTrailingTip.set(
                value=config.getint("Bloc", "blocToTableTrailingTip"))
            self.blocToTableLeadingRoot.set(
                value=config.getint("Bloc", "blocToTableLeadingRoot"))
            self.blocToTableLeadingTip.set(
                value=config.getint("Bloc", "blocToTableLeadingTip"))

            self.hTrailingRoot.set(
                value=config.getfloat("Bloc", "hTrailingRoot"))
            self.hTrailingTip.set(
                value=config.getfloat("Bloc", "hTrailingTip"))
            self.hLeadingRoot.set(
                value=config.getfloat("Bloc", "hLeadingRoot"))
            self.hLeadingTip.set(value=config.getfloat("Bloc", "hLeadingTip"))
            self.hMaxRoot.set(value=config.getfloat("Bloc", "hMaxRoot"))
            self.hMaxTip.set(value=config.getfloat("Bloc", "hMaxTip"))
            self.hMinRoot.set(value=config.getfloat("Bloc", "hMinRoot"))
            self.hMinTip.set(value=config.getfloat("Bloc", "hMinTip"))
            self.hOffset.set(value=config.getfloat("Bloc", "hOffset"))
            self.alignProfil.set(value=config.get("Bloc", "alignProfil"))
            self.hProfil.set(value=config.get("Bloc", "hProfil"))
            try:
                self.angleInRoot.set(
                    value=config.getfloat("Bloc", "angleInRoot"))
                self.angleInTip.set(
                    value=config.getfloat("Bloc", "angleInTip"))
                self.angleOutRoot.set(
                    value=config.getfloat("Bloc", "angleOutRoot"))
                self.angleOutTip.set(
                    value=config.getfloat("Bloc", "angleOutTip"))
            except:
                pass
            """
            self.hMaxRootNorm = config.get("Bloc", "hMaxRootNorm")
            self.hMinRootNorm = config.get("Bloc", "hMinRootNorm")
            self.hLeadingRootNorm = config.get("Bloc", "hLeadingRootNorm")
            self.hMaxTipNorm = config.get("Bloc", "hMaxTipNorm")
            self.hMinTipNorm = config.get("Bloc", "hMinTipNorm")
            self.hLeadingTipNorm = config.get("Bloc", "hLeadingTipNorm")
            """

            self.mSpeedHigh.set(
                value=config.getfloat("Material", "mSpeedHigh"))
            self.mSpeedHalf.set(
                value=config.getfloat("Material", "mSpeedHalf"))
            self.mSpeedLow.set(value=config.getfloat("Material", "mSpeedLow"))
            self.mRadSpHigh.set(
                value=config.getfloat("Material", "mRadSpHigh"))
            self.mRadSpHalf.set(
                value=config.getfloat("Material", "mRadSpHalf"))
            self.mHeatSpHigh.set(
                value=config.getfloat("Material", "mHeatSpHigh"))
            self.mHeatSpLow.set(
                value=config.getfloat("Material", "mHeatSpLow"))
            self.mName.set(value=config.get("Material", "mName"))

            self.tableYY.set(value=config.getfloat("Table", "tableYY"))
            self.tableYG.set(value=config.getfloat("Table", "tableYG"))
            self.tableYD.set(value=config.getfloat("Table", "tableYD"))
            self.cMaxY.set(value=config.getfloat("Table", "cMaxY"))
            self.cMaxZ.set(value=config.getfloat("Table", "cMaxZ"))
            self.vMaxY.set(value=config.getfloat("Table", "vMaxY"))
            self.vMaxZ.set(value=config.getfloat("Table", "vMaxZ"))
            self.tHeatingMax.set(value=config.getfloat("Table", "tHeatingMax"))
            self.tName.set(value=config.get("Table", "tName"))
            self.tComPort.set(value=config.get("Table", "tComPort"))
            self.tBaudrate.set(value=config.get("Table", "tBaudrate"))
            self.tPreHeat.set(value=config.getfloat("Table", "tPreHeat"))
            self.tPostHeat.set(value=config.getfloat("Table", "tPostHeat"))

            self.vCut.set(value=config.getfloat("Cut", "vCut"))
            self.gCodeStart1.set(value=config.get("Cut", "gCodeStart1"))
            self.gCodeStart2.set(value=config.get("Cut", "gCodeStart2"))
            self.gCodeStart3.set(value=config.get("Cut", "gCodeStart3"))
            self.gCodeStart4.set(value=config.get("Cut", "gCodeStart4"))
            self.gCodeEnd1.set(value=config.get("Cut", "gCodeEnd1"))
            self.gCodeEnd2.set(value=config.get("Cut", "gCodeEnd2"))
            self.gCodeEnd3.set(value=config.get("Cut", "gCodeEnd3"))
            self.gCodeEnd4.set(value=config.get("Cut", "gCodeEnd4"))
            self.gCodeLetters.set(value=config.get("Cut", "gCodeLetters"))

            self.gVSpeedNoCut.set(
                value=config.getfloat("Guillotine", "gVSpeedNoCut"))
            self.gHSpeedNoCut.set(
                value=config.getfloat("Guillotine", "gHSpeedNoCut"))
            self.gCuttingSpeed.set(
                value=config.getfloat("Guillotine", "gCuttingSpeed"))
            self.gApplyCalculatedHeating.set(
                value=config.getint("Guillotine", "gApplyCalculatedHeating"))
            self.gHeating.set(value=config.getfloat("Guillotine", "gHeating"))
            self.gType.set(value=config.get("Guillotine", "gType"))
            self.gCuttingWhile.set(
                value=config.get("Guillotine", "gCuttingWhile"))
            self.gVDist.set(value=config.getfloat("Guillotine", "gVDist"))
            self.gHDist.set(value=config.getfloat("Guillotine", "gHDist"))
            """
            x ,y , self.hMaxRootNorm, self.hMinRootNorm , self.hLeadingRootNorm = self.normaliseProfil(
                self.oRootX, self.oRootY, self.cRoot.get(), 0, 0)
            x ,y , self.hMaxTipNorm, self.hMinTipNorm , self.hLeadingTipNorm = self.normaliseProfil(
                self.oTipX, self.oTipY, self.cTip.get(), 0, 0)
            """
            self.validateAllOn = True
            self.validateAll(0)
            self.tProfil.updatePlotRoot()
            self.tProfil.updatePlotTip()

    def uploadTable(self):
        self.tableUploadFileName = filedialog.askopenfilename(\
                            filetypes =(("Table files", "*.tab"),("All files","*.*")),
                            title = "Choose a file to upload a table."
                            )
        if len(self.tableUploadFileName) > 0:
            #config.read('config.ini')
            config = configparser.ConfigParser()
            config.add_section("Table")
            config.add_section("Cut")

            config.read(self.tableUploadFileName)
            self.tableYY.set(value=config.getfloat("Table", "tableYY"))
            self.tableYG.set(value=config.getfloat("Table", "tableYG"))
            self.tableYD.set(value=config.getfloat("Table", "tableYD"))
            self.cMaxY.set(value=config.getfloat("Table", "cMaxY"))
            self.cMaxZ.set(value=config.getfloat("Table", "cMaxZ"))
            self.vMaxY.set(value=config.getfloat("Table", "vMaxY"))
            self.vMaxZ.set(value=config.getfloat("Table", "vMaxZ"))
            self.tHeatingMax.set(value=config.getfloat("Table", "tHeatingMax"))
            self.tName.set(value=config.get("Table", "tName"))
            self.tComPort.set(value=config.get("Table", "tComPort"))
            self.tBaudrate.set(value=config.get("Table", "tBaudrate"))
            self.tPreHeat.set(value=config.getfloat("Table", "tPreHeat"))
            self.tPostHeat.set(value=config.getfloat("Table", "tPostHeat"))

            self.vCut.set(value=config.getfloat("Cut", "vCut"))
            self.gCodeStart1.set(value=config.get("Cut", "gCodeStart1"))
            self.gCodeStart2.set(value=config.get("Cut", "gCodeStart2"))
            self.gCodeStart3.set(value=config.get("Cut", "gCodeStart3"))
            self.gCodeStart4.set(value=config.get("Cut", "gCodeStart4"))
            self.gCodeEnd1.set(value=config.get("Cut", "gCodeEnd1"))
            self.gCodeEnd2.set(value=config.get("Cut", "gCodeEnd2"))
            self.gCodeEnd3.set(value=config.get("Cut", "gCodeEnd3"))
            self.gCodeEnd4.set(value=config.get("Cut", "gCodeEnd4"))
            self.gCodeLetters.set(value=config.get("Cut", "gCodeLetters"))

            self.validateAll(
                20)  # recalculate and redraw bloc, margin and after

    def uploadMaterial(self):
        self.materialUploadFileName = filedialog.askopenfilename(\
                            filetypes =(("Material", "*.mat"),("All files","*.*")),
                            title = "Choose a file to upload a material"
                            )
        if len(self.materialUploadFileName) > 0:
            #config.read('config.ini')
            config = configparser.ConfigParser()
            config.add_section("Material")

            config.read(self.materialUploadFileName)
            self.mSpeedHigh.set(
                value=config.getfloat("Material", "mSpeedHigh"))
            self.mSpeedHalf.set(
                value=config.getfloat("Material", "mSpeedHalf"))
            self.mSpeedLow.set(value=config.getfloat("Material", "mSpeedLow"))
            self.mRadSpHigh.set(
                value=config.getfloat("Material", "mRadSpHigh"))
            self.mRadSpHalf.set(
                value=config.getfloat("Material", "mRadSpHalf"))
            self.mHeatSpHigh.set(
                value=config.getfloat("Material", "mHeatSpHigh"))
            self.mHeatSpLow.set(
                value=config.getfloat("Material", "mHeatSpLow"))
            self.mName.set(value=config.get("Material", "mName"))

            self.validateAll(30)  # recalculate and redraw cutting

    def saveConfig(self):
        config = configparser.ConfigParser()
        config.add_section("Profil")
        config.add_section("Transform")
        config.add_section("Bloc")
        config.add_section("Material")
        config.add_section("Table")
        config.add_section("Cut")
        config.add_section("Guillotine")

        #save all paramaters
        config.set(
            "Profil", "RootX",
            str('[{:s}]'.format(', '.join(
                ['{}'.format(x) for x in self.oRootX]))))
        config.set(
            "Profil", "RootY",
            str('[{:s}]'.format(', '.join(
                ['{}'.format(x) for x in self.oRootY]))))
        config.set(
            "Profil", "RootS",
            str('[{:s}]'.format(', '.join(
                ['{}'.format(x) for x in self.oRootS]))))
        config.set(
            "Profil", "TipX",
            str('[{:s}]'.format(', '.join(['{}'.format(x)
                                           for x in self.oTipX]))))
        config.set(
            "Profil", "TipY",
            str('[{:s}]'.format(', '.join(['{}'.format(x)
                                           for x in self.oTipY]))))
        config.set(
            "Profil", "TipS",
            str('[{:s}]'.format(', '.join(['{}'.format(x)
                                           for x in self.oTipS]))))
        config.set("Profil", "nameRoot", self.nameRoot.get())
        config.set("Profil", "nameTip", self.nameTip.get())

        config.set("Transform", "cRoot", str(self.cRoot.get()))
        config.set("Transform", "cTip", str(self.cTip.get()))
        config.set("Transform", "incidenceRoot", str(self.incidenceRoot.get()))
        config.set("Transform", "thicknessRoot", str(self.thicknessRoot.get()))
        config.set("Transform", "vInvertRoot", str(self.vInvertRoot.get()))
        config.set("Transform", "incidenceTip", str(self.incidenceTip.get()))
        config.set("Transform", "thicknessTip", str(self.thicknessTip.get()))
        config.set("Transform", "vInvertTip", str(self.vInvertTip.get()))
        config.set("Transform", "covering", str(self.covering.get()))
        config.set("Transform", "keepChord", str(self.keepChord.get()))
        config.set("Transform", "smooth", str(self.smooth.get()))
        config.set("Transform", "nbrPoints", str(self.nbrPoints.get()))
        config.set("Transform", "repartition", str(self.repartition.get()))
        config.set("Transform", "reducePoints", str(self.reducePoints.get()))

        config.set("Bloc", "blocLX", str(self.blocLX.get()))
        config.set("Bloc", "blocHZ", str(self.blocHZ.get()))
        config.set("Bloc", "fLeading", str(self.fLeading.get()))
        config.set("Bloc", "fTrailing", str(self.fTrailing.get()))
        config.set("Bloc", "mLeading", str(self.mLeading.get()))
        config.set("Bloc", "mTrailingRoot", str(self.mTrailingRoot.get()))
        config.set("Bloc", "mTrailingTip", str(self.mTrailingTip.get()))
        config.set("Bloc", "leftRightWing", self.leftRightWing.get())
        config.set("Bloc", "blocPosition", self.blocPosition.get())
        config.set("Bloc", "blocToTableLeft", str(self.blocToTableLeft.get()))
        config.set("Bloc", "blocToTableRight",
                   str(self.blocToTableRight.get()))
        config.set("Bloc", "blocToTableTrailingRoot",
                   str(self.blocToTableTrailingRoot.get()))
        config.set("Bloc", "blocToTableTrailingTip",
                   str(self.blocToTableTrailingTip.get()))
        config.set("Bloc", "blocToTableLeadingRoot",
                   str(self.blocToTableLeadingRoot.get()))
        config.set("Bloc", "blocToTableLeadingTip",
                   str(self.blocToTableLeadingTip.get()))

        config.set("Bloc", "hTrailingRoot", str(self.hTrailingRoot.get()))
        config.set("Bloc", "hTrailingTip", str(self.hTrailingTip.get()))
        config.set("Bloc", "hLeadingRoot", str(self.hLeadingRoot.get()))
        config.set("Bloc", "hLeadingTip", str(self.hLeadingTip.get()))
        config.set("Bloc", "hMaxRoot", str(self.hMaxRoot.get()))
        config.set("Bloc", "hMaxTip", str(self.hMaxTip.get()))
        config.set("Bloc", "hMinRoot", str(self.hMinRoot.get()))
        config.set("Bloc", "hMinTip", str(self.hMinTip.get()))
        config.set("Bloc", "hOffset", str(self.hOffset.get()))
        config.set("Bloc", "alignProfil", self.alignProfil.get())
        config.set("Bloc", "hProfil", str(self.hProfil.get()))
        config.set("Bloc", "angleInRoot", str(self.angleInRoot.get()))
        config.set("Bloc", "angleInTip", str(self.angleInTip.get()))
        config.set("Bloc", "angleOutRoot", str(self.angleOutRoot.get()))
        config.set("Bloc", "angleOutTip", str(self.angleOutTip.get()))

        config.set("Material", "mSpeedHigh", str(self.mSpeedHigh.get()))
        config.set("Material", "mSpeedHalf", str(self.mSpeedHalf.get()))
        config.set("Material", "mSpeedLow", str(self.mSpeedLow.get()))
        config.set("Material", "mRadSpHigh", str(self.mRadSpHigh.get()))
        config.set("Material", "mRadSpHalf", str(self.mRadSpHalf.get()))
        config.set("Material", "mHeatSpHigh", str(self.mHeatSpHigh.get()))
        config.set("Material", "mHeatSpLow", str(self.mHeatSpLow.get()))
        config.set("Material", "mName", self.mName.get())

        config.set("Table", "tableYY", str(self.tableYY.get()))
        config.set("Table", "tableYG", str(self.tableYG.get()))
        config.set("Table", "tableYD", str(self.tableYD.get()))
        config.set("Table", "cMaxY", str(self.cMaxY.get()))
        config.set("Table", "cMaxZ", str(self.cMaxZ.get()))
        config.set("Table", "vMaxY", str(self.vMaxY.get()))
        config.set("Table", "vMaxZ", str(self.vMaxZ.get()))
        config.set("Table", "tHeatingMax", str(self.tHeatingMax.get()))
        config.set("Table", "tName", self.tName.get())
        config.set("Table", "tComPort", self.tComPort.get())
        config.set("Table", "tBaudrate", self.tBaudrate.get())
        config.set("Table", "tPreHeat", str(self.tPreHeat.get()))
        config.set("Table", "tPostHeat", str(self.tPostHeat.get()))

        config.set("Cut", "vCut", str(self.vCut.get()))
        config.set("Cut", "gCodeStart1", self.gCodeStart1.get())
        config.set("Cut", "gCodeStart2", self.gCodeStart2.get())
        config.set("Cut", "gCodeStart3", self.gCodeStart3.get())
        config.set("Cut", "gCodeStart4", self.gCodeStart4.get())
        config.set("Cut", "gCodeEnd1", self.gCodeEnd1.get())
        config.set("Cut", "gCodeEnd2", self.gCodeEnd2.get())
        config.set("Cut", "gCodeEnd3", self.gCodeEnd3.get())
        config.set("Cut", "gCodeEnd4", self.gCodeEnd4.get())
        config.set("Cut", "gCodeLetters", self.gCodeLetters.get())

        config.set("Guillotine", "gVSpeedNoCut", str(self.gVSpeedNoCut.get()))
        config.set("Guillotine", "gHSpeedNoCut", str(self.gHSpeedNoCut.get()))
        config.set("Guillotine", "gCuttingSpeed",
                   str(self.gCuttingSpeed.get()))
        config.set("Guillotine", "gApplyCalculatedHeating",
                   str(self.gApplyCalculatedHeating.get()))
        config.set("Guillotine", "gHeating", str(self.gHeating.get()))
        config.set("Guillotine", "gType", self.gType.get())
        config.set("Guillotine", "gCuttingWhile", self.gCuttingWhile.get())
        config.set("Guillotine", "gVDist", str(self.gVDist.get()))
        config.set("Guillotine", "gHDist", str(self.gHDist.get()))


        configSaveFileName = filedialog.asksaveasfilename(title="Save as...", defaultextension="*.ini",\
            filetypes=[("Ini files","*.ini"),("All files", "*")], initialfile=self.configUploadFileName)
        if len(configSaveFileName) > 0:
            config.write(open(configSaveFileName, 'w'))

    def saveTable(self):
        config = configparser.ConfigParser()
        config.add_section("Table")
        config.add_section("Cut")
        config.set("Table", "tableYY", str(self.tableYY.get()))
        config.set("Table", "tableYG", str(self.tableYG.get()))
        config.set("Table", "tableYD", str(self.tableYD.get()))
        config.set("Table", "cMaxY", str(self.cMaxY.get()))
        config.set("Table", "cMaxZ", str(self.cMaxZ.get()))
        config.set("Table", "vMaxY", str(self.vMaxY.get()))
        config.set("Table", "vMaxZ", str(self.vMaxZ.get()))
        config.set("Table", "tHeatingMax", str(self.tHeatingMax.get()))
        config.set("Table", "tName", self.tName.get())
        config.set("Table", "tComPort", self.tComPort.get())
        config.set("Table", "tBaudrate", self.tBaudrate.get())
        config.set("Table", "tPreHeat", str(self.tPreHeat.get()))
        config.set("Table", "tPostHeat", str(self.tPostHeat.get()))

        config.set("Cut", "vCut", str(self.vCut.get()))
        config.set("Cut", "gCodeStart1", self.gCodeStart1.get())
        config.set("Cut", "gCodeStart2", self.gCodeStart2.get())
        config.set("Cut", "gCodeStart3", self.gCodeStart3.get())
        config.set("Cut", "gCodeStart4", self.gCodeStart4.get())
        config.set("Cut", "gCodeEnd1", self.gCodeEnd1.get())
        config.set("Cut", "gCodeEnd2", self.gCodeEnd2.get())
        config.set("Cut", "gCodeEnd3", self.gCodeEnd3.get())
        config.set("Cut", "gCodeEnd4", self.gCodeEnd4.get())
        config.set("Cut", "gCodeLetters", self.gCodeLetters.get())

        if self.tableSaveFileName == None:
            self.tableSaveFileName = self.tableUploadFileName
        self.tableSaveFileName = filedialog.asksaveasfilename(title="Save table as...", defaultextension="*.tab",\
            filetypes=[("Table files","*.tab"),("All files", "*")], initialfile=self.tableSaveFileName)
        if len(self.tableSaveFileName) > 0:
            config.write(open(self.tableSaveFileName, 'w'))

    def saveMaterial(self):
        config = configparser.ConfigParser()
        config.add_section("Material")
        config.set("Material", "mSpeedHigh", str(self.mSpeedHigh.get()))
        config.set("Material", "mSpeedHalf", str(self.mSpeedHalf.get()))
        config.set("Material", "mSpeedLow", str(self.mSpeedLow.get()))
        config.set("Material", "mRadSpHigh", str(self.mRadSpHigh.get()))
        config.set("Material", "mRadSpHalf", str(self.mRadSpHalf.get()))
        config.set("Material", "mHeatSpHigh", str(self.mHeatSpHigh.get()))
        config.set("Material", "mHeatSpLow", str(self.mHeatSpLow.get()))
        config.set("Material", "mName", self.mName.get())

        if self.materialSaveFileName == None:
            self.materialSaveFileName = self.materialUploadFileName
        self.materialSaveFileName = filedialog.asksaveasfilename(title="Save material as...", defaultextension="*.material",\
            filetypes=[("Material files","*.material"),("All files", "*")], initialfile=self.materialSaveFileName)
        if len(self.materialSaveFileName) > 0:
            config.write(open(self.materialSaveFileName, 'w'))

    def validatePart(self):
        self.fTrailing.set(-(self.cRoot.get() - self.cTip.get() -
                             self.fLeading.get()))
        if self.blocPosition.get() == "Left":
            self.tBloc.blocToTableRightBox[
                'validate'] = 'none'  # disable validate, otherwise we call validate inside validate
            self.blocToTableRight.set(self.tableYY.get() - self.tableYG.get() -
                                      self.tableYD.get() -
                                      self.blocToTableLeft.get() -
                                      self.blocLX.get())
            self.tBloc.blocToTableRightBox[
                'validate'] = 'focusout'  #enable after the update
        else:
            self.tBloc.blocToTableRightBox[
                'validate'] = 'none'  # disable validate, otherwise we call validate inside validate
            self.blocToTableLeft.set(self.tableYY.get() - self.tableYG.get() -
                                     self.tableYD.get() -
                                     self.blocToTableRight.get() -
                                     self.blocLX.get())
            self.tBloc.blocToTableRightBox['validate'] = 'focusout'
        self.blocToTableTrailingTip.set(self.blocToTableTrailingRoot.get() -
                                        self.fTrailing.get())
        self.blocToTableLeadingRoot.set(self.blocToTableTrailingRoot.get() +
                                        self.cRoot.get() +
                                        self.mTrailingRoot.get() +
                                        self.mLeading.get())

        self.blocToTableLeadingTip.set(self.blocToTableTrailingTip.get() +
                                       self.cTip.get() +
                                       self.mTrailingTip.get() +
                                       self.mLeading.get())
        #self.mSpeedHalf.set(self.mSpeedHigh.get() / 2) #half speed = high speed /2

    def validateAll(self, level):
        # level is used to avoid to recalculate some data when not needed
        # 0 = calculate all (original profil change)
        # 10 = calculate Transform and after (Transform profil: chord, incidence...)
        # 20 = calculate Bloc/margin and after (change table or bloc position)
        # 30 = calculate cutting (change speed, material)
        if self.initDone and self.validateAllOn:  #avoid validate during the set up of tkinter widgets and when validateAll is disabled
            #try:
            if level == 0:
                self.tProfil.updatePlotRoot()
                self.tProfil.updatePlotTip()

            if level <= 10:
                #create tRoot and tTipX based on oRoot and oTip and chords but not based on bloc and margin
                # draw the view in Transform (= tRoot and tTip)

                if (len(self.oRootX) > 0) and (len(self.oTipX) > 0):
                    #create tRoot and tTipX based on oRoot and oTip and chords but not based on bloc and margin
                    self.tTransform.validateTransform()
                    self.tTransform.updatePlotRoot()
                    self.tTransform.updatePlotTip()

            if level <= 20:
                pass
                #create pRoot and pTipX based on tRoot and tTip and based on Table, bloc and margin
                self.validatePart()
                #print("validatePart is done")
                self.calculatePositions()
                #print("calculatepositions is done")
                # draw the bloc ()
                self.tBloc.updatePlotBloc()
                #print("updatePlotBloc is done")
                #draw the margins
                self.tMargin.updatePlotMargin()
                #print("updatePlotMargin is done")

                #update heating for guillotine
                self.tGuillotine.updateGuillotineHeating()
                #print("updateGuillotineHeating is done")

            if level <= 30:  # calculate Cut based on Material
                self.mSpeedHalf.set(self.mSpeedHigh.get() /
                                    2)  #half speed = high speed /2
                if (len(self.pRootX) > 0) and (len(self.pTipX) > 0):
                    pass
                    #print("begin calculateRedraw")
                    self.tCut.calculateRedraw()
                    #print("end calculateRedraw")
            warningMsg = ""
            if (len(self.oRootX) <= 1) and (len(self.oTipX) <= 1):
                warningMsg = "Root and Tip profiles missing"
            elif len(self.oRootX) <= 1:
                warningMsg = "Root profile missing"
            elif len(self.oTipX) <= 1:
                warningMsg = "Tip profile missing"
            elif (self.tRootS.count(4) + self.tRootS.count(10)) != (
                    self.tTipS.count(4) + self.tTipS.count(10)):
                warningMsg = "Transformed root and tip profiles must have the same number of synchro points"
            self.warningMsg.set(warningMsg)
            #next 2 lines are normally as comment
            #except:

        return True

    def calculatePositions(self):
        #create bRoot and bTipX based on tRoot and tTip and based on bloc and margin
        #calculate Root and Tip offset to apply
        if (len(self.tRootX) > 0) and (len(
                self.tTipX) > 0):  # and (len(self.tRootX) == len(self.tTipX)):
            #calculate relative height of max, min leading
            hMaxRootNorm, hMinRootNorm, hLeadingRootNorm = self.calculateRelativeHeigths(
                self.tRootX, self.tRootY)
            hMaxTipNorm, hMinTipNorm, hLeadingTipNorm = self.calculateRelativeHeigths(
                self.tTipX, self.tTipY)

            #Apply vertical aligment
            if self.alignProfil.get() == "Trailing":
                self.hTrailingRoot.set(self.hProfil.get())
                self.hTrailingTip.set(self.hProfil.get())
            elif self.alignProfil.get() == "Leading":
                self.hTrailingRoot.set(self.hProfil.get() - hLeadingRootNorm)
                self.hTrailingTip.set(self.hProfil.get() - hLeadingTipNorm)
            elif self.alignProfil.get() == "Extrados":
                self.hTrailingRoot.set(self.hProfil.get() - hMaxRootNorm)
                self.hTrailingTip.set(self.hProfil.get() - hMaxTipNorm)
            elif self.alignProfil.get() == "Intrados":
                self.hTrailingRoot.set(self.hProfil.get() - hMinRootNorm)
                self.hTrailingTip.set(self.hProfil.get() - hMinTipNorm)
            self.hLeadingRoot.set(self.hTrailingRoot.get() + hLeadingRootNorm)
            self.hLeadingTip.set(self.hTrailingTip.get() + hLeadingTipNorm)
            self.hMaxRoot.set(self.blocHZ.get() - self.hTrailingRoot.get() -
                              hMaxRootNorm)
            self.hMaxTip.set(self.blocHZ.get() - self.hTrailingTip.get() -
                             hMaxTipNorm)
            self.hMinRoot.set(self.hTrailingRoot.get() + hMinRootNorm)
            self.hMinTip.set(self.hTrailingTip.get() + hMinTipNorm)

            #apply offsets
            self.pRootX = self.tRootX + self.blocToTableTrailingRoot.get(
            ) + self.mTrailingRoot.get()
            self.pTipX = self.tTipX + self.blocToTableTrailingTip.get(
            ) + self.mTrailingTip.get()
            self.pRootY = self.tRootY + self.hOffset.get(
            ) + self.hTrailingRoot.get()
            self.pTipY = self.tTipY + self.hOffset.get(
            ) + self.hTrailingRoot.get()
            self.pRootS = list(self.tRootS)  #create list of synchro
            self.pTipS = list(self.tTipS)  #create list of synchro

    """
    def validateFloat(self, reason, val , name , old,  min , max):
        if reason == "focusout":
            try :  
                v = float(val)
                if v >= float(min) and v <= float(max):
                    
                    return True
                return True    
            except : 
                return False
        elif reason == "focusout":
            if float(val) > float(max):
                print("focus out max exceeded")
                return False
            return self.validateAll()        
        return True
    """

    def normaliseArrayProfil(self, aX, aY, chord):
        #normalise the profil with chord
        if len(aX) > 0:
            minX = np.min(aX)
            maxX = np.max(aX)
            ratio = chord / (maxX - minX)
            aXn = aX * ratio
            aXn = aXn - aXn[0]
            aXn = -1.0 * aXn  # multiply by -1 to reverse the order
            aYn = aY * ratio
            aYn = aYn - aYn[0]
            return aXn, aYn

    """
    def normaliseProfil (self , pX , pY , coord , oY, oZ):
        #normalise the profil with coord and offset of origin
        if len(pX) > 0:
            aX = np.array(pX)
            aY = np.array(pY)
            minX = np.min(aX)
            idxMin = np.where(aX == minX) #return an array with indexes
            maxX = np.max(aX)
            minY = np.min(aY)
            maxY = np.max(aY)
            ratio= coord / ( maxX - minX )  
            aX = aX * ratio
            aX = aX - aX[0]
            aX = -1 * aX # multiply by -1 to reverse the order
            aX = aX + oY
            aY = aY * ratio
            aY = aY - aY[0]
            aY = aY + oZ
            maxh = (maxY / ( maxX - minX ) ) - pY[0]
            minh = (minY / ( maxX - minX ) ) - pY[0] 
            if len(idxMin) > 0 and len(idxMin[0]) > 0:
                r = idxMin[0][0]
                leadingh = (pY[r] / ( maxX - minX ) ) - pY[0]
            else:
                leadingh = 0
                        #print("normalised aX=", aX , "aY=", aY)
            return aX.tolist() , aY.tolist() ,maxh ,minh, leadingh
    """

    def calculateRelativeHeigths(self, pX, pY):
        maxX = np.max(pX)
        idxMax = np.where(pX == maxX)  #return an array with indexes
        minY = np.min(pY)
        maxY = np.max(pY)
        maxh = maxY - pY[0]
        minh = minY - pY[0]
        if len(idxMax) > 0 and len(idxMax[0]) > 0:
            r = idxMax[0][0]
            leadingh = pY[r] - pY[0]
        else:
            leadingh = 0
        return maxh, minh, leadingh
Example #16
0
class Calc:
    def __init__(self, master):
        self.master = master
        self.master.title("Calculator")
        #self.master.geometry("400x300")
        self.master.bind('<Return>', self.get_field)

        self.total = 0
        self.total_var = DoubleVar()
        self.total_var.set(self.total)

        self.expression = ''
        self.exp = StringVar()
        self.exp_label = Label(self.master, textvariable=self.exp)
        self.exp_label.grid(row=0, column=0)

        self.total_label = Label(self.master, textvariable=self.total_var)
        self.total_label.grid(row=0, column=1)

        # optional input field
        self.enter = Entry(self.master)
        self.enter.grid(row=1, column=1)

        # creating operation buttons
        self.plus = Button(self.master,
                           text='+',
                           command=lambda: self.update('+'))
        self.plus.grid(row=4, column=3)

        self.minus = Button(self.master,
                            text='-',
                            command=lambda: self.update('-'))
        self.minus.grid(row=5, column=3)

        self.multiply = Button(self.master,
                               text='*',
                               command=lambda: self.update('*'))
        self.multiply.grid(row=2, column=3)

        self.divide = Button(self.master,
                             text='/',
                             command=lambda: self.update('/'))
        self.divide.grid(row=3, column=3)

        self.delete = Button(self.master,
                             text='del',
                             command=lambda: self.update('del'))
        self.delete.grid(row=1, column=2)

        self.mod = Button(self.master,
                          text='%',
                          command=lambda: self.update('%'))
        self.mod.grid(row=5, column=2)

        self.exponent = Button(self.master,
                               text='^',
                               command=lambda: self.update('**'))
        self.exponent.grid(row=6, column=2)

        self.dot = Button(self.master,
                          text='.',
                          command=lambda: self.update('.'))
        self.dot.grid(row=5, column=1)

        self.equal = Button(self.master,
                            text='=',
                            command=lambda: self.update('='))
        self.equal.grid(row=6, column=3)

        self.reset = Button(self.master,
                            text='C',
                            command=lambda: self.update('C'))
        self.reset.grid(row=1, column=3)

        # start with 2 row and default column
        row = 2
        column = 0
        # create 9 integers buttons
        for num in range(10):
            # add function to every button, on press -> add number to expression
            number = Button(self.master,
                            text=str(num),
                            command=lambda num=num: self.update(str(num)))
            number.grid(row=row, column=column)
            # numbers will be in 3 columns if it's third column -> move to next row
            if column == 2:
                column = 0
                row += 1
            else:
                column += 1

    def get_field(self, event):
        # in input field empty we use existing total
        if self.enter.get() == "":
            self.expression += str(self.total)
        # if input start with operation -> use existing total as first number
        elif self.enter.get()[0] in "+-/*%":
            self.expression = str(self.total_var.get()) + self.enter.get()
        else:
            self.expression += self.enter.get()

        self.exp.set(self.expression)
        self.enter.delete(0, END)

    def update(self, char):
        # clear all
        if char == 'C':
            self.expression = ""
            self.total = 0
        # delete last element from expression
        elif char == "del":
            self.expression = self.expression[:-1]

        elif char == '=':
            try:
                # evaluate expression
                self.total = eval(self.expression)
                self.expression = ""
            except NameError:
                messagebox.showerror("Error", "You entered character")
            except ZeroDivisionError:
                messagebox.showerror("Error", "You cannot divide by zero")
        else:
            # add value to expression
            self.expression += char
            # if expression start with operation -> use existing total as first number
            if self.expression[0] in "+-/*%":
                self.expression = str(float(
                    self.total_var.get())) + self.expression

        self.exp.set(self.expression)
        self.total_var.set(self.total)
        self.enter.delete(0, END)
Example #17
0
class AppRow(MagicSession, Frame):
    """
    Row for each app in mixer.
    handles refreshing the gui if session is changed external.
    handles user input and changing session volume/mute.
    """
    def __init__(self, root_frame_instance):
        super().__init__(volume_callback=self.update_volume,
                         mute_callback=self.update_mute,
                         state_callback=self.update_state)

        self.root_frame_instance = root_frame_instance

        # ______________ DISPLAY NAME ______________
        self.app_name = self.magic_root_session.app_exec

        print(f":: new session: {self.app_name}")
        # ______________ CREATE FRAME ______________
        # super(MagicSession, self).__init__(root_frame_instance)
        Frame.__init__(self, root_frame_instance)

        # _______________ NAME LABEL _______________
        self.name_label = Label(self,
                                text=self.app_name,
                                font=("Consolas", 12, "italic"))

        # _____________ VOLUME SLIDER _____________
        self.volume_slider_state = DoubleVar()

        self.volume_slider = Scale(self,
                                   variable=self.volume_slider_state,
                                   command=self._slide_volume,
                                   from_=0,
                                   to=100,
                                   takefocus=False,
                                   orient=HORIZONTAL)

        # set initial:
        self.volume_slider_state.set(self.volume * 100)

        # ______________ MUTE BUTTON ______________

        self.mute_button_state = StringVar()

        self.mute_button = Button(self,
                                  style="",
                                  textvariable=self.mute_button_state,
                                  command=self._toogle_mute,
                                  takefocus=False)

        # set initial:
        self.update_mute(self.mute)

        # _____________ SESSION STATUS _____________
        self.status_line = Frame(self, style="", width=6)

        # set initial:
        self.update_state(self.state)

        # ________________ SEPARATE ________________
        self.separate = Separator(self, orient=HORIZONTAL)

        # ____________ ARRANGE ELEMENTS ____________
        # set column[1] to take the most space
        # and make all others as small as possible:
        self.columnconfigure(1, weight=1)

        # grid
        self.name_label.grid(row=0, column=0, columnspan=2, sticky="EW")
        self.mute_button.grid(row=1, column=0)
        self.volume_slider.grid(row=1, column=1, sticky="EW", pady=10, padx=20)
        self.separate.grid(row=2, column=0, columnspan=3, sticky="EW", pady=10)
        self.status_line.grid(row=0, rowspan=2, column=2, sticky="NS")

        # _____________ DISPLAY FRAME _____________
        self.pack(pady=0, padx=15, fill='x')

    def update_volume(self, new_volume):
        """
        when volume is changed externally
        (see callback -> AudioSessionEvents -> OnSimpleVolumeChanged )
        """
        # compare if the windows callback is because we set the slider:
        # if so drop update since we made the change
        # and all is already up to date - this will prevent lagg
        print(f"{self.app_name} volume: {new_volume}")
        self.volume_slider_state.set(new_volume * 100)

    def update_mute(self, new_mute):
        """ when mute state is changed by user or through other app """
        if new_mute:
            icon = "🔈"
            self.mute_button.configure(style="Muted.TButton")
        else:
            icon = "🔊"
            self.mute_button.configure(style="Unmuted.TButton")

        # .set is a method of tkinters variables
        # it will change the button text
        print(f"{self.app_name} mute: {icon}")
        self.mute_button_state.set(icon)

    def update_state(self, new_state):
        """
        when status changed
        (see callback -> AudioSessionEvents -> OnStateChanged)
        """
        print(f"{self.app_name} state: {new_state}")
        if new_state == AudioSessionState.Inactive:
            # AudioSessionStateInactive
            self.status_line.configure(style="Inactive.TFrame")

        elif new_state == AudioSessionState.Active:
            # AudioSessionStateActive
            self.status_line.configure(style="Active.TFrame")

        elif new_state == AudioSessionState.Expired:
            # AudioSessionStateExpired
            self.status_line.configure(style="TFrame")
            """when session expires"""
            print(f":: closed session: {self.app_name}")
            self.destroy()

    def _slide_volume(self, value):
        """ when slider moved by user """
        new_volume = float(value) / 100
        # check if new user value really is new: (ttk bug)
        if self.volume != new_volume:
            # since self.volume is true data through windows
            # it will generally differ, but 1.0 == 1
            print(f"with pycaw: {self.app_name} volume: {new_volume}")
            self.volume = new_volume

    def _toogle_mute(self):
        """ when mute button pressed """
        new_mute = self.toggle_mute()

        self.update_mute(new_mute)
Example #18
0
class SettingsFrame(Frame):
    """
    Frame inheritance class for application settings and controls.
    """
    def __init__(self, app, *args, **kwargs):
        """
        Constructor
        """

        self.__app = app  # Reference to main application class
        self.__master = self.__app.get_master()  # Reference to root class (Tk)
        Frame.__init__(self, self.__master, *args, **kwargs)

        #  Initialise up key variables
        self._image_num = 0
        self._image_name = "image"
        self._settype = StringVar()
        self._zoom = DoubleVar()
        self._radius = DoubleVar()
        self._exponent = IntVar()
        self._zx_off = DoubleVar()
        self._zy_off = DoubleVar()
        self._cx_off = DoubleVar()
        self._cy_off = DoubleVar()
        self._maxiter = IntVar()
        self._zx_coord = DoubleVar()
        self._zy_coord = DoubleVar()
        self._theme = StringVar()
        self._shift = IntVar()
        self._themes = None
        self._filename = StringVar()
        self._filepath = None
        self._frames = IntVar()
        self._zoominc = DoubleVar()
        self._autoiter = IntVar()
        self._autosave = IntVar()
        self._validsettings = True

        self.body()

    def body(self):
        """
        Set up frame and widgets.
        """

        # Create settings panel widgets
        # pylint: disable=W0108
        self.lbl_settype = Label(self, text=LBLMODE)
        self.spn_settype = Spinbox(
            self,
            values=("BurningShip", "Tricorn", "Julia", "Mandelbrot"),
            width=8,
            bg=GOOD,
            wrap=True,
            textvariable=self._settype,
        )
        self.lbl_zoom = Label(self, text=LBLZOOM)
        self.ent_zoom = Entry(
            self,
            border=2,
            relief="sunken",
            width=12,
            bg=GOOD,
            justify=RIGHT,
            textvariable=self._zoom,
        )
        self.lbl_zoominc = Label(self, text=LBLZOOMINC, justify=LEFT)
        self.ent_zoominc = Entry(self,
                                 width=5,
                                 border=2,
                                 bg=GOOD,
                                 justify=RIGHT,
                                 textvariable=self._zoominc)
        self.lbl_zx_off = Label(self, text=LBLZXOFF)
        self.ent_zx_off = Entry(
            self,
            border=2,
            relief="sunken",
            width=12,
            bg=GOOD,
            justify=RIGHT,
            textvariable=self._zx_off,
        )
        self.lbl_zy_off = Label(self, text=LBLZYOFF)
        self.ent_zy_off = Entry(
            self,
            border=2,
            relief="sunken",
            width=12,
            bg=GOOD,
            justify=RIGHT,
            textvariable=self._zy_off,
        )
        self.lbl_cx_off = Label(self, text=LBLCX)
        self.ent_cx_off = Entry(
            self,
            border=2,
            relief="sunken",
            width=12,
            bg=GOOD,
            justify=RIGHT,
            textvariable=self._cx_off,
            state=DISABLED,
        )
        self.lbl_cy_off = Label(self, text=LBLCY)
        self.ent_cy_off = Entry(
            self,
            border=2,
            relief="sunken",
            width=12,
            bg=GOOD,
            justify=RIGHT,
            textvariable=self._cy_off,
            state=DISABLED,
        )
        self.lbl_niter = Label(self, text=LBLITER, justify=LEFT)
        self.ent_maxiter = Entry(
            self,
            border=2,
            relief="sunken",
            bg=GOOD,
            width=8,
            justify=RIGHT,
            textvariable=self._maxiter,
        )
        self.chk_autoiter = Checkbutton(self,
                                        text="Auto",
                                        variable=self._autoiter,
                                        onvalue=1,
                                        offvalue=0)
        self.lbl_theme = Label(self, text=LBLTHEME, justify=LEFT)
        self.lbl_radius = Label(self, text=LBLRAD, justify=LEFT)
        self.ent_radius = Entry(
            self,
            border=2,
            relief="sunken",
            bg=GOOD,
            width=8,
            justify=RIGHT,
            textvariable=self._radius,
        )
        self.lbl_exp = Label(self, text=LBLEXP)
        self.spn_exp = Spinbox(
            self,
            border=2,
            relief="sunken",
            bg=GOOD,
            width=4,
            from_=2,
            to=20,
            wrap=True,
            textvariable=self._exponent,
        )
        self.sep_1 = ttk.Separator(
            self,
            orient=HORIZONTAL,
        )
        self.lbx_theme = Listbox(
            self,
            border=2,
            relief="sunken",
            bg=GOOD,
            width=6,
            height=5,
            justify=LEFT,
            exportselection=False,
        )
        self.lbl_shift = Label(self, text=LBLSHIFT, justify=LEFT)
        self.scl_shift = Scale(
            self,
            from_=0,
            to=100,
            orient=HORIZONTAL,
            variable=self._shift,
            border=2,
            relief="sunken",
            sliderlength=20,
            troughcolor=GOOD,
        )
        self.scrollbar = Scrollbar(self, orient=VERTICAL)
        self.lbx_theme.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.lbx_theme.yview)
        self.lbx_theme.select_set(0)
        self.lbx_theme.event_generate("<<ListboxSelect>>")
        self.lbl_coords = Label(self, text="Re, Im", fg="grey")
        self.btn_plot = Button(
            self,
            text=BTNPLOT,
            width=8,
            fg="green",
            command=lambda: self.__app.frm_fractal.plot(),
        )
        self.btn_cancel = Button(
            self,
            text=BTNCAN,
            width=8,
            command=lambda: self.__app.frm_fractal.cancel_press(),
        )
        self.btn_reset = Button(self, text=BTNRST, width=8, command=self.reset)
        self.ent_save = Entry(
            self,
            textvariable=self._filename,
            width=6,
            border=2,
            relief="sunken",
            bg=GOOD,
            justify=LEFT,
        )
        self._filename.set(self._image_name + str(self._image_num))
        self.btn_save = Button(self,
                               text=BTNSAVE,
                               width=8,
                               command=self.save_image)
        self.lbl_auto = Label(self, text=LBLAUTO, justify=LEFT)
        self.btn_autozoom = Button(
            self,
            text=BTNZOOM,
            width=8,
            command=lambda: self.__app.frm_fractal.animate_zoom(),
        )
        self.btn_autospin = Button(
            self,
            text=BTNSPIN,
            width=8,
            command=lambda: self.__app.frm_fractal.animate_spin(),
            state=DISABLED,
        )
        self.chk_autosave = Checkbutton(self,
                                        text=BTNSAVE,
                                        variable=self._autosave,
                                        onvalue=1,
                                        offvalue=0)
        self.lbl_frames = Label(self, text=FRMSTXT)
        self.ent_frames = Entry(self,
                                width=5,
                                border=2,
                                bg=GOOD,
                                justify=RIGHT,
                                textvariable=self._frames)

        # Get list of available themes
        for idx, theme in enumerate(THEMES):
            self.lbx_theme.insert(idx, theme)

        self.body_arrange()  # Position all widgets in frame

        self.reset()  # Reset all settings to their defaults

        self.set_traces(
        )  # Trace entry variables for validation and event handling

    def body_arrange(self):
        """
        Position widgets in frame
        """

        # Position all widgets in their parent frames
        self.btn_plot.grid(column=0,
                           row=1,
                           ipadx=3,
                           ipady=3,
                           sticky=(W),
                           padx=3,
                           pady=3)
        self.btn_cancel.grid(column=1,
                             row=1,
                             ipadx=3,
                             ipady=3,
                             sticky=(W),
                             padx=3,
                             pady=3)
        self.btn_reset.grid(column=2,
                            row=1,
                            ipadx=3,
                            ipady=3,
                            sticky=(W),
                            padx=3,
                            pady=3)
        self.ent_save.grid(column=0,
                           row=2,
                           columnspan=2,
                           sticky=(W, E),
                           padx=3,
                           pady=3)
        self.btn_save.grid(column=2,
                           row=2,
                           ipadx=3,
                           ipady=3,
                           sticky=(W),
                           padx=3,
                           pady=3)
        self.lbl_auto.grid(column=0, row=3, sticky=(W))
        self.btn_autozoom.grid(column=1,
                               row=3,
                               ipadx=3,
                               ipady=3,
                               sticky=(W),
                               padx=3,
                               pady=3)
        self.btn_autospin.grid(column=2,
                               row=3,
                               ipadx=3,
                               ipady=3,
                               sticky=(W),
                               padx=3,
                               pady=3)
        self.lbl_frames.grid(column=0, row=4, sticky=(W))
        self.ent_frames.grid(column=1, row=4, sticky=(W), padx=3, pady=3)
        self.chk_autosave.grid(column=2, row=4, sticky=(W), padx=3, pady=3)
        self.sep_1.grid(column=0, row=5, columnspan=3, pady=5, sticky=(W, E))
        self.lbl_settype.grid(column=0, row=6, sticky=(W))
        self.spn_settype.grid(column=1,
                              row=6,
                              columnspan=2,
                              sticky=(W, E),
                              padx=3,
                              pady=3)
        self.lbl_zoom.grid(column=0, row=7, sticky=(W))
        self.ent_zoom.grid(column=1,
                           row=7,
                           columnspan=2,
                           sticky=(W, E),
                           padx=3,
                           pady=3)
        self.lbl_zoominc.grid(column=0, row=8, sticky=(W))
        self.ent_zoominc.grid(column=1, row=8, sticky=(W), padx=3, pady=3)
        self.lbl_zx_off.grid(column=0, row=9, sticky=(W))
        self.ent_zx_off.grid(column=1,
                             row=9,
                             columnspan=2,
                             sticky=(W, E),
                             padx=3,
                             pady=3)
        self.lbl_zy_off.grid(column=0, row=10, sticky=(W))
        self.ent_zy_off.grid(column=1,
                             row=10,
                             columnspan=2,
                             sticky=(W, E),
                             padx=3,
                             pady=3)
        self.lbl_cx_off.grid(column=0, row=11, sticky=(W))
        self.ent_cx_off.grid(column=1,
                             row=11,
                             columnspan=2,
                             sticky=(W, E),
                             padx=3,
                             pady=3)
        self.lbl_cy_off.grid(column=0, row=12, sticky=(W))
        self.ent_cy_off.grid(column=1,
                             row=12,
                             columnspan=2,
                             sticky=(W, E),
                             padx=3,
                             pady=3)
        self.lbl_niter.grid(column=0, row=13, sticky=(W))
        self.ent_maxiter.grid(column=1, row=13, sticky=(W), padx=3, pady=3)
        self.chk_autoiter.grid(column=2, row=13, sticky=(W), padx=3, pady=3)
        self.lbl_radius.grid(column=0, row=14, sticky=(W))
        self.ent_radius.grid(column=1, row=14, sticky=(W), padx=3, pady=3)
        self.lbl_exp.grid(column=0, row=15, sticky=(W))
        self.spn_exp.grid(column=1, row=15, sticky=(W), padx=3, pady=3)
        self.lbl_theme.grid(column=0, row=16, sticky=(W))
        self.lbx_theme.grid(column=1,
                            row=16,
                            padx=3,
                            pady=3,
                            columnspan=2,
                            sticky=(N, S, W, E))
        self.scrollbar.grid(column=2, row=16, sticky=(N, S, E))
        self.lbl_shift.grid(column=0, row=17, sticky=(W))
        self.scl_shift.grid(column=1,
                            row=17,
                            columnspan=2,
                            padx=3,
                            pady=3,
                            sticky=(W, E))
        self.lbx_theme.bind("<<ListboxSelect>>", self.get_sel_theme)

    def set_traces(self):
        """
        Set up entry variable traces for validation and event handling
        """

        self._validsettings = True
        self._settype.trace("w", self.val_settings)
        self._zoom.trace("w", self.val_settings)
        self._zx_off.trace("w", self.val_settings)
        self._zy_off.trace("w", self.val_settings)
        self._cx_off.trace("w", self.val_settings)
        self._cy_off.trace("w", self.val_settings)
        self._maxiter.trace("w", self.val_settings)
        self._radius.trace("w", self.val_settings)
        self._exponent.trace("w", self.val_settings)
        self._filename.trace("w", self.val_settings)
        self._frames.trace("w", self.val_settings)
        self._zoominc.trace("w", self.val_settings)

    def val_settings(self, *args, **kwargs):
        """
        Validate all user-entered settings.
        (A personal choice but I find this user experience more intuitive
        than the standard validatecommand method for Entry widgets)
        """

        self._validsettings = True
        self.__app.set_status("")

        if self.is_float(self.ent_zoom.get()) and self._zoom.get() > 0:
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_zoom, flg)

        if self.is_float(self.ent_zx_off.get()):
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_zx_off, flg)

        if self.is_float(self.ent_zy_off.get()):
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_zy_off, flg)

        if self.is_float(self.ent_cx_off.get()):
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_cx_off, flg)

        if self.is_float(self.ent_cy_off.get()):
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_cy_off, flg)

        if self.is_integer(self.ent_maxiter.get()) and self._maxiter.get() > 0:
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_maxiter, flg)

        if self.is_float(self.ent_radius.get()) and self._radius.get() > 0:
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_radius, flg)

        if self.is_integer(self.spn_exp.get()) and self._exponent.get() > 1:
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.spn_exp, flg)

        if self.is_integer(self.ent_frames.get()) and self._frames.get() > 0:
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_frames, flg)

        if self.is_float(self.ent_zoominc.get()) and self._zoominc.get() > 0:
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_zoominc, flg)

        if self.is_filename(self.ent_save.get()):
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.ent_save, flg)

        if self.spn_settype.get() in {"Mandelbrot", "Tricorn", "BurningShip"}:
            self.btn_autospin.config(state=DISABLED)
            self.ent_cx_off.config(state=DISABLED)
            self.ent_cy_off.config(state=DISABLED)
            self._cx_off.set(0)
            self._cy_off.set(0)
            flg = GOOD
        elif self.spn_settype.get() == "Julia":
            self.btn_autospin.config(state=NORMAL)
            self.ent_cx_off.config(state=NORMAL)
            self.ent_cy_off.config(state=NORMAL)
            flg = GOOD
        else:
            flg = BAD
        self.flag_entry(self.spn_settype, flg)

    def flag_entry(self, ent, flag):
        """
        Flag entry field as valid or invalid and set global validity status flag.
        This flag is used throughout to determine whether functions can proceed
        or not.
        """

        ent.config(bg=flag)
        if flag == BAD:
            self._validsettings = False
            self.__app.set_status(VALERROR, "red")

    def is_float(self, flag):
        """
        Validate if entry is a float.
        """

        try:
            float(flag)
            return True
        except ValueError:
            return False

    def is_integer(self, flag):
        """
        Validate if entry is a positive integer.
        """

        try:
            int(flag)
            if int(flag) > 0:
                return True
            return False
        except ValueError:
            return False

    def is_filename(self, flag):
        """
        Validate if entry represents a valid filename using a regexp.
        """

        return match("^[\w\-. ]+$", flag) and flag != ""

    def reset(self):
        """
        Reset settings to defaults.
        """

        self._settype.set("Mandelbrot")
        self._zoom.set(0.75)
        self._zx_off.set(-0.5)
        self._zy_off.set(0.0)
        self._cx_off.set(0.0)
        self._cy_off.set(0.0)
        self._maxiter.set(128)
        self._radius.set(2.0)
        self._exponent.set(2)
        self._frames.set(10)
        self._zoominc.set(2.0)
        self._autoiter.set(1)
        self._autosave.set(0)
        self._theme.set("Default")
        self._filename.set("image0")
        self._shift.set(0)
        self.set_sel_theme()

        self.__app.set_status(SETINITTXT)

    def get_sel_theme(self, *args, **kwargs):
        """
        Get selected theme from listbox and set global variable.
        """

        idx = self.lbx_theme.curselection()
        if idx == "":
            idx = 0
        self._theme.set(self.lbx_theme.get(idx))

    def set_sel_theme(self):
        """
        Lookup index of selected theme and highlight that listbox position.
        NB: this requires 'exportselection=False' option to be set on listbox to
        work properly.
        """

        for idx, theme in enumerate(THEMES):
            if theme == self._theme.get():
                self.lbx_theme.activate(idx)
                self.lbx_theme.see(idx)
                break

    def get_settings(self):
        """
        Return all current settings as a dict.
        """

        if not self._validsettings:
            settings = {"valid": self._validsettings}
            return settings

        settings = {
            "settype": self._settype.get(),
            "zoom": self._zoom.get(),
            "zxoffset": self._zx_off.get(),
            "zyoffset": self._zy_off.get(),
            "cxoffset": self._cx_off.get(),
            "cyoffset": self._cy_off.get(),
            "maxiter": self._maxiter.get(),
            "autoiter": self._autoiter.get(),
            "autosave": self._autosave.get(),
            "radius": self._radius.get(),
            "exponent": self._exponent.get(),
            "theme": self._theme.get(),
            "shift": self._shift.get(),
            "filepath": self._filepath,
            "filename": self._filename.get(),
            "frames": self._frames.get(),
            "zoominc": self._zoominc.get(),
            "valid": self._validsettings,
        }
        return settings

    def update_settings(self, **kwargs):
        """
        Update settings from keyword parms.
        """

        if "settype" in kwargs:
            self._settype.set(kwargs["settype"])
        if "zoom" in kwargs:
            self._zoom.set(kwargs["zoom"])
        if "zxoffset" in kwargs:
            self._zx_off.set(kwargs["zxoffset"])
        if "zyoffset" in kwargs:
            self._zy_off.set(kwargs["zyoffset"])
        if "cxoffset" in kwargs:
            self._cx_off.set(kwargs["cxoffset"])
        if "cyoffset" in kwargs:
            self._cy_off.set(kwargs["cyoffset"])
        if "maxiter" in kwargs:
            self._maxiter.set(kwargs["maxiter"])
        if "autoiter" in kwargs:
            self._autoiter.set(kwargs["autoiter"])
        if "autosave" in kwargs:
            self._autosave.set(kwargs["autosave"])
        if "radius" in kwargs:
            self._radius.set(kwargs["radius"])
        if "exponent" in kwargs:
            self._exponent.set(kwargs["exponent"])
        if "filepath" in kwargs:
            self._filepath.set(kwargs["filepath"])
        if "filename" in kwargs:
            self._filename.set(kwargs["filename"])
        if "frames" in kwargs:
            self._frames.set(kwargs["frames"])
        if "zoominc" in kwargs:
            self._zoominc.set(kwargs["zoominc"])
        if "theme" in kwargs:
            self._theme.set(kwargs["theme"])
            self.set_sel_theme()
        if "shift" in kwargs:
            self._shift.set(kwargs["shift"])

    def set_filepath(self):
        """
        Sets filepath for saved files for the duration of this session.
        """

        default = os.getcwd()  # Default _filepath is current working directory
        if self._filepath is None:
            self._filepath = filedialog.askdirectory(title=SAVETITLE,
                                                     initialdir=default,
                                                     mustexist=True)
            if self._filepath == "":
                self._filepath = None  # User cancelled

        return self._filepath

    def save_image(self):
        """
        Save image as PNG file to selected filepath and automatically increment default
        image name. NB: currently this will overwrite any existing file of the same
        name without warning.
        """

        # Bug out if the settings are invalid
        settings = self.__app.frm_settings.get_settings()
        if not settings["valid"]:
            return

        # Check if image has been created
        image = self.__app.frm_fractal.mandelbrot.get_image()
        if image is None:
            self.__app.set_status(NOIMGERROR, "red")
            return

        # Set _filename and path
        if self.set_filepath() is None:  # User cancelled
            return
        fname = self._filename.get()
        fqname = self._filepath + "/" + fname

        # Save the image along with its metadata
        try:
            # image.write(fqname + ".png", format="png")
            image.save(fqname + ".png", format="png")
            self.save_metadata()
        except OSError:
            self.__app.set_status(SAVEERROR, "red")
            self._filepath = None
            return

        self._image_num += 1
        self._filename.set(self._image_name + str(self._image_num))
        self.__app.set_status(IMGSAVETXT + fqname + ".png", "green")

        # Return focus to image frame
        self.__app.frm_fractal.focus_set()

    def save_metadata(self):
        """
        Save json file containing meta data associated with image,
        allowing it to be imported and reproduced.
        """

        if self._filepath is None:
            if self.set_filepath() is None:  # User cancelled
                return

        fname = self._filename.get()
        fqname = self._filepath + "/" + fname
        filename = fqname + ".json"
        createtime = strftime("%b %d %Y %H:%M:%S %Z", gmtime())

        jsondata = {
            MODULENAME: {
                "filename": fqname + ".png",
                "created": createtime,
                "settype": self._settype.get(),
                "zoom": self._zoom.get(),
                "zoominc": self._zoominc.get(),
                "frames": self._frames.get(),
                "escradius": self._radius.get(),
                "exponent": self._exponent.get(),
                "maxiter": self._maxiter.get(),
                "zxoffset": self._zx_off.get(),
                "zyoffset": self._zy_off.get(),
                "cxoffset": self._cx_off.get(),
                "cyoffset": self._cy_off.get(),
                "theme": self._theme.get(),
                "shift": self._shift.get(),
            }
        }

        try:
            with open(filename, "w") as outfile:
                dump(jsondata, outfile)
        except OSError:
            self.__app.set_status(METASAVEERROR, "red")
            self._filepath = None

        # Return focus to image frame
        self.__app.frm_fractal.focus_set()

    def import_metadata(self):
        """
        Update settings from imported json metadata file.
        """

        # Select and read file
        try:
            default = os.getcwd()
            filepath = filedialog.askopenfilename(
                initialdir=default,
                title=SELTITLE,
                filetypes=(("json files", "*.json"), ("all files", "*.*")),
            )
            if filepath == "":  # User cancelled
                return
            with open(filepath, "r") as infile:
                jsondata = infile.read()
        except OSError:
            self.__app.set_status(OPENFILEERROR, "red")
            return

        # Parse file
        try:

            settings = loads(jsondata).get(MODULENAME)

            # Set plot parameters
            self._settype.set(settings.get("settype", "Mandelbrot"))
            self._zoom.set(settings.get("zoom", 1))
            self._zoominc.set(settings.get("zoominc", 2.0))
            self._frames.set(settings.get("frames", 10))
            self._radius.set(settings.get("escradius", 2.0))
            self._exponent.set(settings.get("exponent", 2))
            self._maxiter.set(settings.get("maxiter", 256))
            self._zx_off.set(settings.get("zxoffset", 0))
            self._zy_off.set(settings.get("zyoffset", 0))
            self._cx_off.set(settings.get("cxoffset", 0))
            self._cy_off.set(settings.get("cyoffset", 0))
            self._theme.set(settings.get("theme", "Default"))
            self._shift.set(settings.get("shift", 0))

        except OSError:
            self.__app.set_status(BADJSONERROR, "red")
            return

        self.set_sel_theme()

        fbase = os.path.basename(filepath)
        filename, fileext = os.path.splitext(fbase)
        self.__app.set_status(
            "Metadata file " + filename + fileext + METAPROMPTTXT, "green")

        # Return focus to image frame
        self.__app.frm_fractal.focus_set()
Example #19
0
class SmashCalc(ttk.Frame):
    def __init__(self, parent):
        print("SmashCalc __init__")
        ttk.Frame.__init__(self, parent)
        self.parent = parent
        self.chars_url = "{}/characters".format(api_url)
        self.get_chars()
        self.init_ui()
        self.rage = 1
        self.move_name = ""
        self.enemy_weight = -1

    def init_ui(self):
        print("UI init")
        self.set_title()
        # charbox = ttk.Listbox()
        print("making frames")
        print(type(self.parent))
        self.content = ttk.Frame(self.parent, padding=10)
        print(type(self.content))
        self.content.grid(column=0, row=0, sticky="NSEW")
        # self.user_image
        # self.enemy_image
        print("making boxes")
        self.init_user()
        self.init_enemy()
        self.init_move()

    def init_user(self):
        self.user_frame = ttk.Frame(self.content, borderwidth=2)
        self.user_frame.grid(column=0, row=0)
        self.user_frame['padding'] = (20, 10)
        # self.user_frame['borderwidth'] = 2
        self.user_frame['relief'] = 'sunken'

        self.user_label = ttk.Label(self.user_frame, text="Attacker")
        self.user_label.grid(column=0, row=0, columnspan=2, rowspan=1)

        self.userchar = StringVar()
        self.userchar.set('none')
        self.user_menu = ttk.Combobox(self.user_frame)
        self.user_menu.grid(column=0, row=1, columnspan=2, rowspan=1)
        self.user_menu['values'] = self.chars
        self.user_menu.bind('<<ComboboxSelected>>', self.on_user_menu_input)

        self.userdmg = StringVar()
        self.userdmg.set('')
        self.userdmg.trace('w', self.on_user_damage_input)

        self.rage_box = ttk.Label(self.user_frame, text="Rage multiplier:")
        self.rage_box.grid(column=0, row=5, columnspan=2, sticky="W")
        self.user_percentbox = ttk.Label(self.user_frame, text="%:")
        self.user_percentbox.grid(column=0,
                                  row=2,
                                  columnspan=1,
                                  rowspan=1,
                                  sticky="W")
        validate_cmd = (self.register(self.on_percent_validate), '%d', '%S',
                        '%P')
        self.user_damage_entry = ttk.Entry(self.user_frame,
                                           textvariable=self.userdmg,
                                           validate="key",
                                           validatecommand=validate_cmd)
        self.user_damage_entry.grid(column=1,
                                    row=2,
                                    columnspan=1,
                                    rowspan=1,
                                    sticky="W")

    def init_enemy(self):
        self.enemy_frame = ttk.Frame(self.content, borderwidth=2)
        self.enemy_frame.grid(column=1, row=0)
        self.enemy_frame['padding'] = (20, 10)
        # self.enemy_frame['borderwidth'] = 2
        self.enemy_frame['relief'] = 'sunken'

        self.enemy_label = ttk.Label(self.enemy_frame, text="Target")
        self.enemy_label.grid(column=0, row=0, columnspan=2, rowspan=1)

        self.enemychar = StringVar()
        self.enemychar.set('none')

        self.enemy_menu = ttk.Combobox(self.enemy_frame)
        self.enemy_menu.grid(column=0, row=1, columnspan=2, rowspan=1)
        self.enemy_menu['values'] = self.chars
        self.enemy_menu.bind('<<ComboboxSelected>>', self.on_enemy_menu_input)

        self.enemydmg = StringVar()
        self.enemydmg.set('')
        self.enemydmg.trace('w', self.on_enemy_damage_input)

        self.enemy_percentbox = ttk.Label(self.enemy_frame, text="%:")
        self.enemy_percentbox.grid(column=0,
                                   row=2,
                                   columnspan=1,
                                   rowspan=1,
                                   sticky="W")
        validate_cmd = (self.register(self.on_percent_validate), '%d', '%S',
                        '%P')
        self.enemy_damage_entry = ttk.Entry(self.enemy_frame,
                                            textvariable=self.enemydmg,
                                            validate="key",
                                            validatecommand=validate_cmd)
        self.enemy_damage_entry.grid(column=1,
                                     row=2,
                                     columnspan=1,
                                     rowspan=1,
                                     sticky="W")
        self.weight_box = ttk.Label(self.enemy_frame, text="Weight:")
        self.weight_box.grid(column=0, row=3, columnspan=2, sticky="W")
        self.is_crouch = DoubleVar()
        self.is_smash = DoubleVar()
        self.is_meteor = DoubleVar()
        self.is_crouch.set(1)
        self.is_smash.set(1)
        self.is_meteor.set(1)
        self.crouch_check = ttk.Checkbutton(self.enemy_frame,
                                            variable=self.is_crouch,
                                            text="Crouching",
                                            command=self.on_crouch_check,
                                            offvalue=1,
                                            onvalue=0.85)
        self.smash_check = ttk.Checkbutton(self.enemy_frame,
                                           variable=self.is_smash,
                                           text="Charging smash",
                                           command=self.on_smash_check,
                                           offvalue=1,
                                           onvalue=1.2)
        self.meteor_check = ttk.Checkbutton(self.enemy_frame,
                                            variable=self.is_meteor,
                                            text="Grounded meteor",
                                            command=self.on_meteor_check,
                                            offvalue=1,
                                            onvalue=0.8)
        self.crouch_check.grid(column=2, row=1, sticky="W")
        self.smash_check.grid(column=2, row=2, sticky="W")
        self.meteor_check.grid(column=2, row=3, sticky="W")

    def init_move(self):
        self.move_frame = ttk.Frame(self.content, borderwidth=2)
        self.move_frame['padding'] = (20, 10)
        # self.move_frame['borderwidth'] = 2
        self.move_frame['relief'] = 'sunken'
        self.move_frame.grid(column=0, row=1, columnspan=2, sticky="WE")
        self.move_label = ttk.Label(self.move_frame, text="Attacking move:")
        self.move_label.grid(column=0, row=0, sticky="W")
        self.move_menu = ttk.Combobox(self.move_frame)
        self.move_menu.grid(column=0,
                            row=1,
                            columnspan=1,
                            rowspan=1,
                            sticky="NSEW")
        self.move_menu['width'] = 40
        # self.moves = []
        # self.move_menu['values'] = self.moves
        self.move_menu.bind('<<ComboboxSelected>>', self.on_move_menu_input)
        self.move_info_frame = MoveFrame(self.move_frame)

    def get_chars(self):
        print("getting all char data")
        response = urllib.request.urlopen(
            self.chars_url).read().decode('utf-8')
        chars_data = json.loads(response)
        self.chars = []
        self.name_to_id = {}
        for char in chars_data:
            self.chars.append(char['name'])
            self.name_to_id[char['name']] = char['id']

    def set_title(self, title=""):
        if (title != ""):
            self.parent.title("SmashCalc - {}".format(title))
        else:
            self.parent.title("SmashCalc")

    def on_user_menu_input(self, val):
        self.userchar = self.user_menu.get()
        print("user entry! {}".format(self.userchar))
        moves_url = "{}/characters/{}/moves".format(
            api_url, self.name_to_id[self.userchar])
        response = urllib.request.urlopen(moves_url).read().decode('utf-8')
        self.moves_data = json.loads(response)
        self.moves = []
        self.move_to_id = {}
        self.moves_dict = {}
        for move in self.moves_data:
            print(type(move))
            print(move)
            # print(type(self.move_to_id))
            # print(self.move_to_id)
            # print("{}, {}".format(move['name'], move['id']))
            self.moves.append(move['name'])
            # self.move_to_id[move['name']] = move['id']
            self.moves_dict[move['name']] = move
        self.set_title(self.userchar)
        self.move_info_frame.clear_fields()
        # print(self.moves)
        # print(self.move_to_id)
        # print(self.moves_data)
        self.move_menu['values'] = self.moves
        # self.movebox =
        # self.move_data = {}
        self.update_move_fields(clear=True)

    def on_enemy_menu_input(self, val):
        self.enemychar = self.enemy_menu.get()
        print("enemy entry! {}".format(self.enemychar))
        data_url = "{}/characters/{}/characterattributes".format(
            api_url, self.name_to_id[self.enemychar])
        response = urllib.request.urlopen(data_url).read().decode('utf-8')
        attr_data = json.loads(response)
        # print(attr_data)
        for item in attr_data:
            print(item)
            print(item['name'])
            if (item['name'] == 'WEIGHT VALUE'):
                self.enemy_weight = float(item['value'])
                print("weight of {} is {}".format(self.enemychar,
                                                  self.enemy_weight))
        self.weight_box['text'] = "Weight: {}".format(int(self.enemy_weight))
        self.update_kb()

    def on_move_menu_input(self, val):
        # data_url = "{}/characters/{}/characterattributes".format(
        #            api_url, self.name_to_id[self.enemychar])
        # response = urllib.request.urlopen(data_url).read().decode('utf-8')
        # self.move_data = json.loads(response)
        # print(self.name_to_id)
        # print(self.moves_data[0])
        self.move_name = self.move_menu.get()
        print(self.moves_dict[self.move_menu.get()])
        self.update_move_fields()
        # self.BKB
        # self.name
        # self.
        self.update_kb()

    def on_user_damage_input(self, *args):
        print("user percent changed!")
        # self.percent = self.userdmg.get()
        # print(self.percent)
        print(self.userdmg.get())
        if (self.userdmg.get() == ''):
            return
        dmg = float(self.userdmg.get())
        if (dmg < 35):
            self.rage = 1
        elif (dmg > 150):
            self.rage = 1.15
        else:
            self.rage = 1 + (dmg - 35) * (.15) / (115)
        print("rage is now {}".format(self.rage))
        self.rage_box['text'] = "Rage multiplier: {: <4.2f}x".format(self.rage)
        self.update_kb()

    def on_enemy_damage_input(self, *args):
        print("enemy percent changed!")
        if (self.enemydmg.get() != ''):
            self.update_kb()

    # validate_cmd = (self.register(self.on_percent_validate), '%d', '%S', '%P')
    def on_percent_validate(self, why, change, new_value):
        print("validation")
        if (why == '1'):
            print("reason: insertion")
        elif (why == '0'):
            print("reason: deletion")
        else:
            print("UKNOWN REASON: {}".format(why))

        if (new_value == ''):
            print("empty box")
            return True
        try:
            float(new_value)
            # self.percent = float(new_value)
        except ValueError:
            return False
        # print(self.percent)
        # if (self.percent < 35):
        #     self.rage = 1
        # elif (self.percent > 150):
        #     self.rage = 1.15
        # else:
        #     self.rage = 1 + (self.percent - 35) * (.15) / (115)
        # print("rage is now {}".format(self.rage))
        # self.rage_box['text'] = "Rage multiplier: {: <4.2f}x".format(self.rage)

        # self.update_kb()

        return True

    def on_crouch_check(self):
        print("crouch: {}".format(self.is_crouch))
        self.update_kb()

    def on_smash_check(self):
        print("smash: {}".format(self.is_smash))
        self.update_kb()

    def on_meteor_check(self):
        print("meteor: {}".format(self.is_meteor))
        self.update_kb()

    def update_move_fields(self, clear=False):
        if (clear):
            self.move_name = ""
            self.kb = 0
            return
        else:
            print(self.moves_dict)
            print("move name: {}".format(self.move_name))
            print(self.moves_dict[self.move_name])
            self.move_info_frame.set_fields(self.moves_dict[self.move_name])
            self.update_kb()

    # set_kb(self, target_weight, target_percent, staleness=1, misc_variable=1):
    def update_kb(self):
        print("update_kb?")
        if (self.move_name != "" and self.move_info_frame.empty == False
                and self.enemy_weight > 0):
            print("updating")
            misc_var = float(self.rage) * self.is_crouch.get(
            ) * self.is_smash.get() * self.is_meteor.get()
            # Using onvalue and offvalue so don't need these.
            # if (self.is_crouch):
            #     misc_var = misc_var * 0.85
            # if (self.is_smash):
            #     misc_var = misc_var * 1.2
            # if (self.is_meteor):
            #     misc_var = misc_var * 0.8

            # self.move_info_frame.set_kb(self.enemy_weight, self.enemy_damage_entry.get(), staleness=1, misc_variable=misc_var)
            self.move_info_frame.set_kb(self.enemy_weight,
                                        float(self.enemydmg.get()),
                                        staleness=1,
                                        misc_variable=misc_var)
        else:
            print("nevermind")
            pass
Example #20
0
class Calculator():
    def __init__(self, master):
        self.master = master
        master.title('Calculator')
        self.total = 0.0
        self.entered_number = 0.0

        self.total_label_text = DoubleVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master,
                           validate="key",
                           validatecommand=(vcmd, '%P'))

        self.add_button = Button(master,
                                 text="+",
                                 command=lambda: self.update("add"))
        self.subtract_button = Button(master,
                                      text="-",
                                      command=lambda: self.update("subtract"))
        self.reset_button = Button(master,
                                   text="Clear",
                                   command=lambda: self.update("reset"))
        self.multiply_button = Button(master,
                                      text="*",
                                      command=lambda: self.update("multiply"))

        # LAYOUT

        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)

        self.entry.grid(row=1, column=0, columnspan=3, sticky=W + E)

        self.add_button.grid(row=2, column=0, sticky=W + E)
        self.subtract_button.grid(row=2, column=1, sticky=W + E)
        self.reset_button.grid(row=2, column=2, sticky=W + E)
        self.multiply_button.grid(row=3, column=1, sticky=W + E)

    def validate(self, new_text):
        if not new_text:  # the field is being cleared
            self.entered_number = 0.0
            return True
        try:
            self.entered_number = float(new_text)
            return True
        except ValueError:
            return False

    def update(self, method):
        if method == "add":
            self.total += self.entered_number
        elif method == "subtract":
            self.total -= self.entered_number
        elif method == "multiply":
            self.total *= self.entered_number
        else:  # reset
            self.total = 0

        self.total_label_text.set(self.total)
        self.entry.delete(0, END)
class TkMainGui(ttk.Frame):
    def __init__(self, root, default_folder=""):
        ttk.Frame.__init__(self, root, padding="3 3 12 12")
        self.default_folder = default_folder

        logger.debug("Create main frame")
        self.grid(column=0, row=0, sticky=(N, W, E, S))
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        logger.debug("Create variable")
        self.program_path = StringVar()
        file_path = os.path.join(self.default_folder, "30kV ElementsView.exe")
        self.program_path.set(file_path)

        self.basename = StringVar()
        self.basename.set("test")

        self.acquisition_mode = StringVar()
        self.acquisition_mode.set(ACQUISITION_MODE_MANUAL)

        self.number_spectra = IntVar()
        self.number_spectra.set(100)

        self.delay_spectrum_s = DoubleVar()
        self.delay_spectrum_s.set(1)

        self.overwrite = BooleanVar()
        self.overwrite.set(False)

        self.fast_acquisition = BooleanVar()
        self.fast_acquisition.set(False)

        self.is_top_window = BooleanVar()
        self.is_top_window.set(False)
        self.is_manual_acquisition_button = BooleanVar()
        self.is_manual_acquisition_button.set(False)
        self.is_save_as = BooleanVar()
        self.is_save_as.set(False)

        self.results_text = StringVar()

        widget_width = 40

        logger.debug("Create program button")
        row_id = 1
        file_path_entry = ttk.Entry(self,
                                    width=widget_width,
                                    textvariable=self.program_path)
        file_path_entry.grid(column=2, row=row_id, sticky=(W, E))
        ttk.Button(self,
                   width=widget_width,
                   text="Select ElementView program file",
                   command=self.open_element_view_program).grid(column=3,
                                                                row=row_id,
                                                                sticky=W)

        logger.debug("Create basename label and edit entry")
        row_id += 1
        basename_label = ttk.Label(self,
                                   width=widget_width,
                                   text="basename: ",
                                   state="readonly")
        basename_label.grid(column=2, row=row_id, sticky=(W, E))
        basename_entry = ttk.Entry(self,
                                   width=widget_width,
                                   textvariable=self.basename)
        basename_entry.grid(column=3, row=row_id, sticky=(W, E))

        row_id += 1
        acquisition_mode_label = ttk.Label(self,
                                           width=widget_width,
                                           text="Acquisition mode: ",
                                           state="readonly")
        acquisition_mode_label.grid(column=2, row=row_id, sticky=(W, E))
        acquisition_mode_entry = ttk.Combobox(
            self,
            width=widget_width,
            textvariable=self.acquisition_mode,
            values=[ACQUISITION_MODE_LIVE, ACQUISITION_MODE_MANUAL])
        acquisition_mode_entry.grid(column=3, row=row_id, sticky=(W, E))

        row_id += 1
        number_spectra_label = ttk.Label(self,
                                         width=widget_width,
                                         text="Number of spectra: ",
                                         state="readonly")
        number_spectra_label.grid(column=2, row=row_id, sticky=(W, E))
        number_spectra_entry = ttk.Entry(self,
                                         width=widget_width,
                                         textvariable=self.number_spectra)
        number_spectra_entry.grid(column=3, row=row_id, sticky=(W, E))

        row_id += 1
        delay_spectrum_label = ttk.Label(
            self,
            width=widget_width,
            text="Delay between of spectrum (s): ",
            state="readonly")
        delay_spectrum_label.grid(column=2, row=row_id, sticky=(W, E))
        delay_spectrum_entry = ttk.Entry(self,
                                         width=widget_width,
                                         textvariable=self.delay_spectrum_s)
        delay_spectrum_entry.grid(column=3, row=row_id, sticky=(W, E))

        row_id += 1
        ttk.Checkbutton(self,
                        width=widget_width,
                        text="Overwrite file",
                        variable=self.overwrite).grid(column=3,
                                                      row=row_id,
                                                      sticky=(W, E))

        row_id += 1
        ttk.Checkbutton(self,
                        width=widget_width,
                        text="Fast acquisition",
                        variable=self.fast_acquisition).grid(column=3,
                                                             row=row_id,
                                                             sticky=(W, E))

        row_id += 1
        ttk.Button(self,
                   width=widget_width,
                   text="Find ElementView",
                   command=self.find_element_view).grid(column=3,
                                                        row=row_id,
                                                        sticky=W)

        logger.debug("ElementView elements")
        row_id += 1
        ttk.Checkbutton(self,
                        width=widget_width,
                        text="Top window",
                        variable=self.is_top_window,
                        state=DISABLED).grid(column=3,
                                             row=row_id,
                                             sticky=(W, E))
        row_id += 1
        ttk.Checkbutton(self,
                        width=widget_width,
                        text="Manual acquisition",
                        variable=self.is_manual_acquisition_button,
                        state=DISABLED).grid(column=3,
                                             row=row_id,
                                             sticky=(W, E))
        row_id += 1
        ttk.Checkbutton(self,
                        width=widget_width,
                        text="Save as",
                        variable=self.is_save_as,
                        state=DISABLED).grid(column=3,
                                             row=row_id,
                                             sticky=(W, E))

        row_id += 1
        self.start_button = ttk.Button(self,
                                       width=widget_width,
                                       text="Start script",
                                       command=self.start_script,
                                       state=DISABLED)
        self.start_button.grid(column=3, row=row_id, sticky=W)

        row_id += 1
        results_label = ttk.Label(self,
                                  textvariable=self.results_text,
                                  state="readonly")
        results_label.grid(column=2, row=row_id, sticky=(W, E))

        for child in self.winfo_children():
            child.grid_configure(padx=5, pady=5)

        basename_entry.focus()
        self.results_text.set("Start")

    def open_element_view_program(self):
        logger.debug("open_element_view_program")

        file_path = filedialog.askopenfilename(filetypes=(("executable file",
                                                           "*.exe"), ),
                                               initialdir=self.default_folder)
        logger.debug(file_path)
        self.program_path.set(file_path)

    def find_element_view(self):
        try:
            app = Application(backend="win32").connect(
                path=self.program_path.get())
            logger.info("Application connected")
            # logger.info("app: {}".format(app.print_control_identifiers(depth=1)))

            try:
                top_window = app.top_window()
                top_window.wait("exists enabled visible ready")
                self.is_top_window.set(True)
                logger.info("top_window: {}".format(
                    top_window.print_control_identifiers(depth=1)))

                try:
                    logger.info("Button2: {}".format(
                        top_window.Button2.print_control_identifiers(depth=1)))
                    self.is_manual_acquisition_button.set(True)
                except Exception as message:
                    logger.error(message)
                    self.is_manual_acquisition_button.set(False)

                try:
                    top_window.menu_select("File -> Save")
                    logger.info("File->Save")
                    app.Comment.wait("exists enabled visible ready")
                    logger.info(app.Comment.print_control_identifiers())
                    # app.CommentEdit.Edit.SetEditText("auto script")
                    app.Comment.OK.click()
                    logger.info("Comment")

                    app['Save As'].wait("exists enabled visible ready")
                    logger.info(
                        app['Save As'].print_control_identifiers(depth=2))
                    app['Save As'].Cancel.click()
                    logger.info("Cancel")
                    self.is_save_as.set(True)
                except Exception as message:
                    logger.error(message)
                    self.is_save_as.set(False)

            except Exception as message:
                logger.errror(message)
                self.is_top_window.set(False)
                self.is_manual_acquisition_button.set(False)
                self.is_save_as.set(False)

        except (TimeoutError, AppNotConnected,
                ProcessNotFoundError) as message:
            logger.error(message)
            self.is_top_window.set(False)
            self.is_manual_acquisition_button.set(False)
            self.is_save_as.set(False)

        if self.is_top_window.get() and self.is_manual_acquisition_button.get(
        ) and self.is_save_as.get():
            self.results_text.set("ElementView elements found")
            self.start_button.config(state=NORMAL)
        else:
            self.results_text.set("ElementView elements NOT found")
            self.start_button.config(state=DISABLED)

    def start_script(self):
        self.save_spectra()

    def save_spectra(self):
        acquisition_mode = self.acquisition_mode.get()
        safe_acquisition = not self.fast_acquisition.get()
        overwrite = self.overwrite.get()

        if self.fast_acquisition.get():
            Timings.Fast()
            Timings.window_find_timeout = 2

        if acquisition_mode == ACQUISITION_MODE_MANUAL:
            self.results_text.set("Manual save")
        if acquisition_mode == ACQUISITION_MODE_LIVE:
            self.results_text.set("Live save")

        app = Application(backend="win32").connect(
            path=self.program_path.get())
        logger.info("Application connected")

        top_window = app.window(title_re=".*ElementsView.*")
        if safe_acquisition:
            top_window.wait("exists enabled visible ready")

        for spectrum_id in range(1, self.number_spectra.get() + 1):
            logger.info("Spectrum id: {:d}".format(spectrum_id))

            if safe_acquisition:
                top_window.wait("exists enabled visible ready")

            if acquisition_mode == ACQUISITION_MODE_MANUAL:
                top_window.Button2.click()

                time.sleep(self.delay_spectrum_s.get())

            if safe_acquisition:
                top_window.wait("exists enabled visible ready")
            top_window.menu_select("File -> Save")

            if safe_acquisition:
                app.Comment.wait("exists enabled visible ready")
                app.CommentEdit.Edit.SetEditText("auto script")
            app.Comment.OK.click()

            save_as_window = app['Save As']
            if safe_acquisition:
                save_as_window.wait("exists enabled visible ready")
            file_name = "%s_%i.elv" % (self.basename.get(), spectrum_id)
            save_as_window.Edit.SetEditText(file_name)
            save_as_window.Save.click()

            if overwrite:
                try:
                    window_confirm = app['Confirm Save As']
                    if safe_acquisition:
                        window_confirm.wait("exists enabled visible ready")
                    if self.overwrite.get():
                        window_confirm.Yes.click()
                    else:
                        window_confirm.No.click()
                        save_as_window.Cancel.click()
                        self.results_text.set("Cancel save file already exist")
                        return
                except Exception as message:
                    logger.error(message)

        logger.info("Done")
        self.results_text.set("Done")
Example #22
0
    def __init__(self, master, par=False):
        """
        GUI for selecting default parameters - will write parameters to file \
        of users choosing.

        :type master: Tk
        :param master: Tkinter window
        :type par: EQcorrscanParameters
        :param par: Default parameters to start-up with.
        """
        from tkinter import Label, Button, Entry, DoubleVar, StringVar, IntVar
        from tkinter import BooleanVar, OptionMenu, Checkbutton
        import tkMessageBox
        from eqcorrscan.utils import parameters
        from obspy import UTCDateTime
        import warnings

        # Set the default par, only if they don't already exist.
        if not par:
            par = parameters.EQcorrscanParameters([''], 2, 10, 4, 100, 2,
                                                  '1900-01-01', '2300-01-01',
                                                  '', 'seishub', 4, False, '',
                                                  'jpg', False, 8, 'MAD', 6)
        # Callback functions for all variables (ugly)

        def update_template_names(*args):
            par.template_names = [
                name.strip() for name in template_names.get().split(',')
            ]
            template_names.set(', '.join(par.template_names))

        def update_lowcut(*args):
            par.lowcut = lowcut.get()
            lowcut.set(par.lowcut)

        def update_highcut(*args):
            par.highcut = highcut.get()
            if par.highcut >= 0.5 * par.samp_rate:
                msg = ('Highcut must be less than the Nyquist, setting to ' +
                       str((par.samp_rate / 2.0) - 1))
                tkMessageBox.showwarning(title="Nyquist error", message=msg)
                par.highcut = (par.samp_rate / 2.0) - 1
            highcut.set(par.highcut)

        def update_filt_order(*args):
            par.filt_order = filt_order.get()
            filt_order.set(par.filt_order)

        def update_samp_rate(*args):
            par.samp_rate = samp_rate.get()
            if par.highcut >= 0.5 * par.samp_rate:
                msg = ('Highcut must be less than the Nyquist, setting to ' +
                       str((par.samp_rate / 2.0) - 1))
                tkMessageBox.showwarning(title="Nyquist error", message=msg)
                par.highcut = (par.samp_rate / 2.0) - 1
                highcut.set(par.highcut)
            samp_rate.set(par.samp_rate)

        def update_debug(*args):
            par.debug = debug.get()
            debug.set(par.debug)

        def update_startdate(*args):
            par.startdate = UTCDateTime(startdate.get())
            startdate.set(str(par.startdate))

        def update_enddate(*args):
            par.enddate = UTCDateTime(enddate.get())
            enddate.set(str(par.enddate))

        def update_archive(*args):
            par.archive = archive.get()
            archive.set(par.archive)

        def update_arc_type(*args):
            par.arc_type = arc_type.get()
            arc_type.set(par.arc_type)

        def update_cores(*args):
            par.cores = cores.get()
            cores.set(par.cores)

        def update_plotvar(*args):
            par.plotvar = plotvar.get()
            plotvar.set(par.plotvar)

        def update_plot_format(*args):
            par.plot_format = plot_format.get()
            plot_format.set(par.plot_format)

        def update_tempdir(*args):
            par.tempdir = tempdir.get()
            tempdir.set(par.tempdir)

        def update_threshold(*args):
            par.threshold = threshold.get()
            threshold.set(par.threshold)

        def update_threshold_type(*args):
            par.threshold_type = threshold_type.get()
            threshold_type.set(par.threshold_type)

        def update_plotdir(*args):
            par.plotdir = plotdir.get()
            plotdir.set(par.plotdir)

        def update_trigger_interval(*args):
            par.trigger_interval = trigger_interval.get()
            trigger_interval.set(par.trigger_interval)

        # Set some grid parameters
        nrows = 25
        ncolumns = 3
        self.master = master
        master.title("EQcorrscan parameter setup")
        self.label = Label(master, text="Alpha GUI for default setup")
        self.label.grid(column=0, columnspan=ncolumns, row=0)

        # Set up parameter input
        self.t_names_label = Label(master, text="Template names", anchor='e')
        self.t_names_label.grid(column=0, row=1, sticky='e')
        template_names = StringVar()
        template_names.set(', '.join(par.template_names))
        self.t_names_box = Entry(master, bd=2, textvariable=template_names)
        self.t_names_box.grid(column=1, row=1)
        template_names.trace("w", update_template_names)
        self.t_names_lookup = Button(
            master,
            text="Lookup",
            command=lambda: self.get_template_names(par))
        self.t_names_lookup.grid(column=2, row=1)

        self.lowcut_label = Label(master, text="Lowcut (Hz)", anchor='e')
        self.lowcut_label.grid(column=0, row=2, sticky='e')
        lowcut = DoubleVar()
        lowcut.set(par.lowcut)
        self.lowcut_box = Entry(master, bd=2, textvariable=lowcut)
        self.lowcut_box.grid(column=1, row=2)
        lowcut.trace("w", update_lowcut)

        self.highcut_label = Label(master, text="Highcut (Hz)", anchor='e')
        self.highcut_label.grid(column=0, row=3, sticky='e')
        highcut = DoubleVar()
        highcut.set(par.highcut)
        self.highcut_box = Entry(master, bd=2, textvariable=highcut)
        self.highcut_box.grid(column=1, row=3)
        highcut.trace("w", update_highcut)

        self.filt_order_label = Label(master, text="Filter order")
        self.filt_order_label.grid(column=0, row=4, sticky='e')
        filt_order = DoubleVar()
        filt_order.set(par.filt_order)
        self.filt_order_box = Entry(master, bd=2, textvariable=filt_order)
        self.filt_order_box.grid(column=1, row=4)
        filt_order.trace("w", update_filt_order)

        self.samp_rate_label = Label(master, text="Sample rate (Hz)")
        self.samp_rate_label.grid(column=0, row=5, sticky='e')
        samp_rate = DoubleVar()
        samp_rate.set(par.samp_rate)
        self.samp_rate_box = Entry(master, bd=2, textvariable=samp_rate)
        self.samp_rate_box.grid(column=1, row=5)
        samp_rate.trace("w", update_samp_rate)

        self.debug_label = Label(master, text="Debug")
        self.debug_label.grid(column=0, row=6, sticky='e')
        debug = IntVar()
        debug.set(par.debug)
        self.debug_box = Entry(master, bd=2, textvariable=debug)
        self.debug_box.grid(column=1, row=6)
        debug.trace("w", update_debug)

        self.startdate_label = Label(master, text="Start date (yyyy-mm-dd)")
        self.startdate_label.grid(column=0, row=6, sticky='e')
        startdate = StringVar()
        startdate.set(par.startdate)
        self.startdate_box = Entry(master, bd=2, textvariable=startdate)
        self.startdate_box.grid(column=1, row=6)
        startdate.trace("w", update_startdate)

        self.enddate_label = Label(master, text="End date (yyyy-mm-dd)")
        self.enddate_label.grid(column=0, row=8, sticky='e')
        enddate = StringVar()
        enddate.set(par.enddate)
        self.enddate_box = Entry(master, bd=2, textvariable=enddate)
        self.enddate_box.grid(column=1, row=8)
        enddate.trace("w", update_enddate)

        self.archive_label = Label(master, text="Archive")
        self.archive_label.grid(column=0, row=9, sticky='e')
        archive = StringVar()
        archive.set(par.archive)
        self.archive_box = Entry(master, bd=2, textvariable=archive)
        self.archive_box.grid(column=1, row=9)
        archive.trace("w", update_archive)
        self.archive_lookup = Button(master,
                                     text="Lookup",
                                     command=lambda: self.get_archive(par))
        self.archive_lookup.grid(column=2, row=9)

        self.arc_type_label = Label(master, text="Archive type")
        self.arc_type_label.grid(column=0, row=10, sticky='e')
        arc_type = StringVar()
        arc_type.set(par.arc_type)
        self.arc_type_box = OptionMenu(master, arc_type, "seishub", "fdsn",
                                       "day_vols")
        self.arc_type_box.grid(column=1, row=10, sticky='w,e')
        arc_type.trace("w", update_arc_type)

        self.cores_label = Label(master, text="Number of cores")
        self.cores_label.grid(column=0, row=11, sticky='e')
        cores = IntVar()
        cores.set(par.cores)
        self.cores_box = Entry(master, bd=2, textvariable=cores)
        self.cores_box.grid(column=1, row=11)
        cores.trace("w", update_cores)

        self.plotvar_label = Label(master, text="Plotting on/off")
        self.plotvar_label.grid(column=0, row=12, sticky='e')
        plotvar = BooleanVar()
        plotvar.set(par.plotvar)
        self.plotvar_box = Checkbutton(master,
                                       text='Plot on',
                                       var=plotvar,
                                       onvalue=True,
                                       offvalue=False)
        self.plotvar_box.grid(column=1, row=12)
        plotvar.trace("w", update_plotvar)

        self.plotdir_label = Label(master, text="Plot directory")
        self.plotdir_label.grid(column=0, row=13, sticky='e')
        plotdir = StringVar()
        plotdir.set(par.plotdir)
        self.plotdir_box = Entry(master, bd=2, textvariable=plotdir)
        self.plotdir_box.grid(column=1, row=13)
        plotdir.trace("w", update_plotdir)
        self.plotdir_lookup = Button(master,
                                     text="Lookup",
                                     command=lambda: self.get_plotdir(par))
        self.plotdir_lookup.grid(column=2, row=13)

        self.plot_format_label = Label(master, text="Plot format")
        self.plot_format_label.grid(column=0, row=14, sticky='e')
        plot_format = StringVar()
        plot_format.set(par.plot_format)
        self.plot_format_box = OptionMenu(master, plot_format, "jpg", "eps",
                                          "pdf", "png")
        self.plot_format_box.grid(column=1, row=14, sticky='w,e')
        plot_format.trace("w", update_plot_format)

        self.tempdir_label = Label(master, text="Temporary directory")
        self.tempdir_label.grid(column=0, row=15, sticky='e')
        tempdir = StringVar()
        tempdir.set(par.tempdir)
        self.tempdir_box = Entry(master, bd=2, textvariable=tempdir)
        self.tempdir_box.grid(column=1, row=15)
        tempdir.trace("w", update_tempdir)
        self.tempdir_lookup = Button(master,
                                     text="Lookup",
                                     command=lambda: self.get_tempdir(par))
        self.tempdir_lookup.grid(column=2, row=15)

        self.threshold_label = Label(master, text="Threshold")
        self.threshold_label.grid(column=0, row=16, sticky='e')
        threshold = DoubleVar()
        threshold.set(par.threshold)
        self.threshold_box = Entry(master, bd=2, textvariable=threshold)
        self.threshold_box.grid(column=1, row=16)
        threshold.trace("w", update_threshold)

        self.threshold_type_label = Label(master, text="Threshold type")
        self.threshold_type_label.grid(column=0, row=17, sticky='e')
        threshold_type = StringVar()
        threshold_type.set(par.threshold_type)
        self.threshold_type_box = OptionMenu(master, threshold_type, "MAD",
                                             "absolute", "av_chan_corr")
        self.threshold_type_box.grid(column=1, row=17, sticky='w,e')
        threshold_type.trace("w", update_threshold_type)

        self.trigger_interval_label = Label(master,
                                            text="Minimum trigger " +
                                            "interval (s)")
        self.trigger_interval_label.grid(column=0, row=18, sticky='e')
        trigger_interval = DoubleVar()
        trigger_interval.set(par.trigger_interval)
        self.trigger_interval_box = Entry(master,
                                          bd=2,
                                          textvariable=trigger_interval)
        self.trigger_interval_box.grid(column=1, row=18)
        trigger_interval.trace("w", update_trigger_interval)

        # End of user editable section, now we have read/write buttons
        self.read_button = Button(master,
                                  text="Read parameters",
                                  command=lambda: self.read_par(master))
        self.read_button.grid(column=0, row=nrows - 2, sticky='w,e')

        self.write_button = Button(master,
                                   text="Write parameters",
                                   command=lambda: self.write_par(par))
        self.write_button.grid(column=1, row=nrows - 2, sticky='w,e')
Example #23
0
class Gui(Frame):
    def __init__(self, control, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.config(padx=2)
        self.queue = Queue()
        self.control = control
        self.disabledWhileRunning = []

        self.formulae = list(map(lambda t: StringVar(self, t), ["x/22.5+4", "50-x*50/180"]))
        self.executionTime = DoubleVar(self, "360")
        self.programSpeed = IntVar(self, "292")
        self.maxTravel = IntVar(self, "-200000")
        self.loadSettings()

        self.createWidgets()
        self.thread = None

    def compileFormulae(self):
        rv = []
        for f in self.formulae:
            body = "def formula5480750923(x):\n  return " + f.get()
            l = {}
            try:
                exec(body, {}, l)
            except:
                rv.append(None)
                continue
            compiled = l["formula5480750923"]
            compiled(0)
            rv.append(compiled)
        return rv

    def plotFormulae(self):
        try:
            compiled = self.compileFormulae()
        except:
            return
        for g in self.graphs:
            g.points = []
        self.canvas.x.end = self.executionTime.get()
        self.canvas.clear()
        for x in range(self.canvas.x.start, int(self.canvas.x.end)):
            point = []
            for c in range(len(compiled)):
                v = None
                if compiled[c]:
                    v = compiled[c](x)
                assert isinstance(v, float)
                point.append(v)
            self.__addPoint__(x, point)
        self.canvas.update()

    def __start__(self):
        self.canvas.x.end = self.executionTime.get()
        pumps = self.compileFormulae()
        self.setValues()
        self.control.mover.setSpeed(abs(int(self.programSpeed.get())))
        start_time = float(self.current_time.get())

        def calcPumpValues(time):
            values = list(map(lambda x: x(time), pumps))
            self.__addPoint__(time, values)
            self.current_time.set(time)
            return values

        def thFunc():
            try:
                for g in self.graphs:
                    g.points = []
                self.control.executeProgram(start_time, calcPumpValues)
            finally:
                self.invoke(self.__enableControls__)

        self.__disableControls__()
        self.canvas.clear()
        self.thread = Thread(target=thFunc, name="Control")
        self.thread.start()

    def __enableControls__(self):
        for e in self.disabledWhileRunning:
            e.config(state=NORMAL)

    def __disableControls__(self):
        for e in self.disabledWhileRunning:
            e.config(state="disabled")

    def __addPoint__(self, x, values):
        for v in values:
            assert isinstance(v, float)

        def c():
            for i in range(len(self.canvas.graphs)):
                self.canvas.graphs[i].addPoint(x, values[i])

        self.invoke(c)

    def invoke(self, callable):
        self.after_idle(callable)

    def __stop__(self):
        self.control.stop()

    def __quit__(self):
        def quitting():
            self.__stop__()
            if self.thread and self.thread.is_alive():
                print("Thread is active")
                return False
            self.quit()
            return True

        run_repeating(self, quitting)

    def __move__(self, steps):
        speed = int(self.speed.get())
        if speed < 0:
            speed *= -1
            self.speed.set(speed)
        self.control.mover.setSpeed(speed)
        self.control.mover.go(steps)

    def __up__(self):
        steps = int(self.steps.get())
        self.__move__(steps)

    def __down__(self):
        steps = int(self.steps.get())
        self.__move__(-steps)

    def showValues(self):
        self.maxTravel.set(self.control.mover.maxTravel)
        self.executionTime.set(self.control.fullTime)
        self.programSpeed.set(self.control.mover.getSpeed())

    def setValues(self):
        self.control.mover.maxTravel = int(self.maxTravel.get())
        self.control.fullTime = float(self.executionTime.get())
        self.control.mover.setSpeed(abs(int(self.programSpeed.get())))

    def loadSettings(self):
        config = Config()
        try:
            config.read()
        except KeyError:
            pass
        config.configureControl(self.control)
        for i in range(len(self.formulae)):
            self.formulae[i].set(config.formulae[i])
        self.showValues()

    def saveSettings(self):
        self.setValues()
        config = Config()
        config.getFromControl(self.control)
        for i in range(len(self.formulae)):
            config.formulae[i] = self.formulae[i].get()
        config.write()

    def createWidgets(self):
        panel = Frame(self, name="mainMenu")
        panel.grid(sticky=W)
        Button(panel, name="quit", text="Выход", command=self.__quit__).grid(row=0, column=0)
        Button(panel, name="reconnect", text="Пересоединение", command=self.control.reconnect).grid(row=0, column=1)
        b = Button(panel, text="Загрузить", command=self.loadSettings)
        b.grid(row=0, column=2)
        self.disabledWhileRunning.append(b)
        b = Button(panel, text="Сохранить", command=self.saveSettings)
        b.grid(row=0, column=3)
        self.disabledWhileRunning.append(b)
        panel = LabelFrame(self, text="Прямое управление стаканом", name="motor")
        panel.grid(sticky=W)
        b = Button(panel, text="Вверх", command=self.__up__, name="up")
        b.grid(row=0, column=0)
        self.disabledWhileRunning.append(b)
        b = Button(panel, text="Вниз", command=self.__down__, name="down")
        b.grid(row=1, column=0)
        self.disabledWhileRunning.append(b)
        Label(panel, text="Шаг:").grid(sticky=E, row=0, column=1)
        self.steps = IntVar(self, "10000")
        Entry(panel, textvariable=self.steps, width=6).grid(sticky=W, row=0, column=2)
        Label(panel, text="Скорость:").grid(sticky=E, row=1, column=1)
        self.speed = IntVar(self, "2000")
        Entry(panel, textvariable=self.speed, width=6).grid(sticky=W, row=1, column=2)
        self.position = IntVar(self, "1000")

        def readPosition():
            try:
                self.position.set(self.control.mover.getPosition())
            except (ConnectionResetError, Timeout):
                pass

        run_repeating(self, readPosition, 10000)
        b = Button(panel, text="Прочитать положение", command=readPosition)
        b.grid(row=0, column=3, columnspan=2)
        self.disabledWhileRunning.append(b)
        Label(panel, text="Положение:").grid(sticky=E, row=1, column=3)
        Entry(panel, textvariable=self.position, width=8, state="disabled").grid(sticky=W, row=1, column=4)

        panel = LabelFrame(self, text="Программа", name="program")
        program = panel
        panel.grid(sticky=W + E)
        panel.columnconfigure(1, weight=1)
        row = 0
        for f in self.formulae:
            columns, rows = self.grid_size()
            Label(panel, text="Насос %d:" % (row + 1)).grid(row=row, column=0, sticky=E)
            e = Entry(panel, textvariable=f)
            e.grid(sticky=E + W, row=row, column=1)
            self.disabledWhileRunning.append(e)
            f.trace("w", lambda *x: self.after_idle(self.plotFormulae))
            row += 1
        panel = Frame(program, name="mover")
        panel.grid(columnspan=2, sticky=W)
        Label(panel, text="Максимальное смещение:").grid(sticky=E)
        Entry(panel, textvariable=self.maxTravel).grid(sticky=W, row=0, column=1)
        Label(panel, text="Скорость:").grid(sticky=E)
        Entry(panel, textvariable=self.programSpeed).grid(sticky=W, row=1, column=1)
        Label(panel, text="Время выполнения (в секундах):").grid(sticky=E)
        e = Entry(panel, textvariable=self.executionTime)
        e.grid(sticky=W, row=2, column=1)
        self.current_time = DoubleVar(self, "0")
        Label(panel, text="Текущее время:").grid(sticky=E)
        e = Entry(panel, textvariable=self.current_time)
        e.grid(sticky=W, row=3, column=1)
        self.disabledWhileRunning.append(e)
        self.executionTime.trace("w", lambda *x: self.plotFormulae())

        panel = Frame(program, name="bottom")
        panel.grid(columnspan=2, sticky=W)
        row = 0
        startButton = Button(panel, name="start", text="Старт", command=self.__start__)
        startButton.grid(row=row, column=0)
        self.disabledWhileRunning.append(startButton)
        Button(panel, text="Стоп", command=self.__stop__).grid(row=row, column=1)

        self.canvas = GraphCanvas(self)
        self.graphs = (Graph(self.canvas), Graph(self.canvas))

        self.canvas.x.end = 100
        self.canvas.y.end = 24
        self.plotFormulae()
        self.canvas.grid(sticky=E + W + S + N)
        columns, rows = self.grid_size()
        self.columnconfigure(columns - 1, weight=1)
        self.rowconfigure(rows - 1, weight=1)
    def initui(self):

        self.parent.title("Light pollution map")
        self.style = Style()
        self.style.theme_use("alt")

        self.grid(row=0, column=0)

        padding = {'padx':'5', 'pady':'5'}
        big_heading_font = ("Arial", 14, 'bold')
        small_heading_font = ("Arial", 10, 'bold')

        # Create frames.
        # There are three frames for settings - preprocessing, convolve, and contour.
        # Each also has an image frame underneath it.
        # Layout is as follows:
        #
        #             --------------------------------------------------------------------------
        #             |                 |                 |                 |                  |
        #             |                 |                 |                 |                  |
        #             |   import_body   |   process_body  |   contour_body  |   export_body    |
        #             |                 |                 |                 |                  |
        #             |                 |                 |                 |                  |
        #             --------------------------------------------------------------------------

        # Settings frames

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

        import_body = Frame(self, relief=RAISED, borderwidth=1)
        import_body.grid(row=0, column=0, sticky=N+S+E+W)

        process_body = Frame(self, relief=RAISED, borderwidth=1)
        process_body.grid(row=0, column=1, sticky=N+S+E+W)

        contour_body = Frame(self, relief=RAISED, borderwidth=1)
        contour_body.grid(row=0, column=2, sticky=N+S+E+W)

        export_body = Frame(self, relief=RAISED, borderwidth=1)
        export_body.grid(row=0, column=3, sticky=N+S+E+W)

         # =============================================================================================================
        #
        # Contents of load_image_frame
        #
        # =============================================================================================================

        # Heading

        processing_frame_header = Label(import_body, text="Import", font=big_heading_font)
        processing_frame_header.grid(row=0, column=0, sticky=N, **padding)

        filename_variable = StringVar()

        # Import image

        import_canvas = Canvas(import_body, width=canvas_size, height=canvas_size, background='black')
        import_canvas.grid(row=1, column=0, sticky=N, **padding)

        # Load file method

        def choosefile():
            filename_variable.set(filedialog.askopenfilename(parent=import_body))
            image = Image.open(filename_variable.get())
            thumbnail = create_thumbnail(image, canvas_size)
            import_canvas.create_image(0, 0, image=thumbnail, anchor=NW)

        load_image_button = Button(import_body, text="Import image", command=choosefile)
        load_image_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding)
        import_body.rowconfigure(2, weight=1)

        # =============================================================================================================
        #
        # Contents of processing_frame
        #
        # =============================================================================================================

        processing_frame_header = Label(process_body, text="Process", font=big_heading_font)
        processing_frame_header.grid(row=0, column=0, columnspan=2, sticky=N, **padding)

        clipping_variable = IntVar()

        constants_label = Label(process_body, text="Clipping",
                                font=("Arial", 10, 'bold'))
        constants_label.grid(row=1, column=0, sticky=E, **padding)

        clipping_label = Label(process_body, text="Remove pixels with \n brightness under")
        clipping_label.grid(row=2, column=0, sticky=E, **padding)

        clipping_entry = Entry(process_body, textvariable=clipping_variable, width=4)
        clipping_entry.grid(row=2, column=1, sticky=W, **padding)

        clipping_variable.set(value=default_clipping_value)

        convolve_header = Label(process_body, text="Kernel", font=small_heading_font)
        convolve_header.grid(row=4, column=0, sticky=E, **padding)

        kernel_size_variable = IntVar()

        kernel_size_label = Label(process_body, text="Convolve kernel size", justify=RIGHT)
        kernel_size_label.grid(row=5, column=0, sticky=E, **padding)

        kernel_size_entry = Entry(process_body, textvariable=kernel_size_variable, width=4)
        kernel_size_entry.grid(row=5, column=1, sticky=W, **padding)
        kernel_size_variable.set(value=default_kernel_size)

        # Constants for convolve equation

        constants_label = Label(process_body, text="Falloff",
                                font=("Arial", 10, 'bold'))
        constants_label.grid(row=6, column=0, sticky=E, **padding)

        constant_a_label = Label(process_body, text="Constant A:")
        constant_b_label = Label(process_body, text="Constant B:")
        constant_c_label = Label(process_body, text="Constant C:")

        constant_a_label.grid(row=7, column=0, sticky=E, **padding)
        constant_b_label.grid(row=8, column=0, sticky=E, **padding)
        constant_c_label.grid(row=9, column=0, sticky=E, **padding)

        constant_a_variable = DoubleVar()
        constant_b_variable = DoubleVar()
        constant_c_variable = DoubleVar()

        constant_a_entry = Entry(process_body, textvariable=constant_a_variable, width=4)
        constant_b_entry = Entry(process_body, textvariable=constant_b_variable, width=4)
        constant_c_entry = Entry(process_body, textvariable=constant_c_variable, width=4)

        constant_a_variable.set(default_constant_a)
        constant_b_variable.set(default_constant_b)
        constant_c_variable.set(default_constant_c)

        constant_a_entry.grid(row=7, column=1, **padding)
        constant_b_entry.grid(row=8, column=1, **padding)
        constant_c_entry.grid(row=9, column=1, **padding)

        constants_note = Label(process_body, text="Falloff equation is (Ax^B)-C", font=("Arial", 9))
        constants_note.grid(row=10, column=0, columnspan=2, sticky=E, **padding)

        # Start button!

        def process():
            print("Filename was " + filename_variable.get())
            image_data =  process_image(filename=filename_variable.get(),
                                        kernel_size=kernel_size_variable.get(),
                                        clipping_value=clipping_variable.get(),
                                        constant_a=constant_a_variable.get(),
                                        constant_b=constant_b_variable.get(),
                                        constant_c=constant_c_variable.get()
                                        )

            image_data = Image.open("processed_image.png")
            thumbnail = create_thumbnail(image_data, canvas_size)
            export_canvas.create_image(0, 0, image=thumbnail, anchor=NW)

        start_button = Button(process_body, text="Process image", command=process)
        start_button.grid(row=11, column=0, columnspan=3, sticky=E+W+S, **padding)
        process_body.rowconfigure(11, weight=1)

        # =============================================================================================================
        #
        # Contents of contour_frame
        #
        # =============================================================================================================

        contour_header = Label(contour_body, text="Contour", font=big_heading_font)
        contour_header.grid(row=0, column=0, sticky=S, columnspan=2, **padding)

        contour_note = Label(contour_body, text="(optional)")
        contour_note.grid(row=1, column=0, sticky=S, columnspan=2)

        scale_options = {"width":"5", "length":"150"}
        slider_padding = {"padx":"2", "pady":"0"}

        scale_list = []
        scale_values_list = []

        default_scale_values = [5, 7, 10, 20, 30, 40, 60, 100, 200]

        for i in range(9):
            scale = Scale(contour_body, from_=0, to_=255, orient=HORIZONTAL, **scale_options)
            scale.grid(row=i+2, column=0, columnspan=2, sticky=S, **slider_padding)
            scale.set(default_scale_values[i])
            scale_list.append(scale)

        for scale in scale_list:
            print(scale)
            print(type(scale))
            #print(scale.get())

        def contour():

            scale_values_list.clear()

            for scale in scale_list:
                scale_values_list.append(scale.get())

            contour_image(scale_values_list)

            image_data = Image.open("Contoured_image.png")
            thumbnail = create_thumbnail(image_data, canvas_size)
            export_canvas.create_image(0, 0, image=thumbnail, anchor=NW)

        contour_button = Button(contour_body, text="Contour image", command=contour)
        contour_button.grid(row=11, column=0, columnspan=2, sticky=E+S+W, **padding)
        contour_body.rowconfigure(11, weight=1)
        contour_body.columnconfigure(1, weight=1)

        # =============================================================================================================
        #
        # Contents of export_body
        #
        # =============================================================================================================

        filename_export_variable = StringVar()

        def export_file():
            filename_options = {}
            filename_options['filetypes'] = [('PNG', '.png')]
            filename_options['initialfile'] = 'output.png'
            filename_options['parent'] = self
            filename_export_variable.set(filedialog.asksaveasfilename(**filename_options))
            image_data = Image.open("Contoured_image.png")
            image_data.save(filename_export_variable.get())

        export_header = Label(export_body, text="Export", font=big_heading_font)
        export_header.grid(row=0, column=0, sticky=N, **padding)

        export_canvas = Canvas(export_body, width=canvas_size, height=canvas_size, background='black')
        export_canvas.grid(row=1, column=0, **padding)

        export_button = Button(export_body, text="Export image", command=export_file)
        export_button.grid(row=2, column=0, columnspan=2, sticky=E+W+S, **padding)
        export_body.rowconfigure(2, weight=1)
Example #25
0
class FloatEntry(IntegerEntry):
    """Float class for entry

    Parameters
    ----------
    parent : str
        parent handle
    lf_text : str
        text on LabelFrame
    l_limit : float
        lower limit
    u_limit : float
        upper limit
    def_inp : str
        default text
    colour : str
        frame colour
    mod : boolean
        enable or disable state switch

    Returns
    -------
    float
    """
    def __init__(self,
                 parent,
                 lf_text,
                 l_limit,
                 u_limit,
                 def_inp="",
                 colour='brown',
                 mod=False):
        '''
        #self.parent = parent
        #self.lf_text = lf_text
        #self.mod = mod
        #self.def_inp=def_inp
        #self.colour = colour
        #self.l_limit = l_limit
        #self.u_limit = u_limit
        '''
        super().__init__(parent, lf_text, l_limit, u_limit, def_inp, colour,
                         mod)

        self.out_var = DoubleVar()
        self.out_var.set(def_inp)

        self.construct(colour)
        self.make_entry()
        self.limits()

    def is_okay(self, text, inp, ind):
        """ validation function

        Parameters
        ----------
        text : str
            text if allowed
        inp : str
            current input

        Returns
        -------
        boolean
        """
        if text in ("", "-", ".", "-."):
            return True
        try:
            float(text)
        except ValueError:
            return False
        return True
Example #26
0
class HOPSProgressbar(HOPSWidget):
    def __init__(self, window, task='Process', length=None):

        self.task = task
        if not length:
            length = 4 / window.log.plt2screen_w

        widget = Frame(window.main_frame)
        self.progress = DoubleVar(widget, value=0)
        self.progressbar = Progressbar(widget,
                                       variable=self.progress,
                                       length=length *
                                       window.root.winfo_screenwidth(),
                                       orient=HORIZONTAL,
                                       maximum=100,
                                       mode='determinate',
                                       value=0)

        self.task_label = Label(widget,
                                text=self.task +
                                ' - 000.0 % - time left: 00:00:00')
        self.element_label = Label(widget, text=' ')

        self.task_label.pack()
        self.progressbar.pack()
        self.element_label.pack()

        self.start_time = 0
        self.skip_time = 0
        self.total_iterations = 1
        self.current_iteration = 0
        self.show_at = [0]

        HOPSWidget.__init__(self, window, widget, 'Progressbar')

    def reset(self):

        self.progress.set(0)
        self.task_label.configure(text=self.task +
                                  ' - 000.0 % - time left: 00:00:00')

    def initiate(self, total_iterations, show_every=1):

        if isinstance(total_iterations, list):
            self.total_iterations = len(total_iterations)
            self.elements = total_iterations
        else:
            self.total_iterations = int(total_iterations)
            self.elements = None

        self.current_iteration = 0
        self.start_time = time.time()

        self.show_at = list(
            range(1, self.total_iterations,
                  int(show_every))) + [int(self.total_iterations)]

    def show_message(self, message):
        if message != self.element_label['text']:
            self.element_label.configure(text=message)

    def update(self, step=1, skip=0):

        self.current_iteration += step
        self.skip_time += skip

        delta_time = time.time() - self.start_time - self.skip_time

        time_left = str(
            datetime.timedelta(
                seconds=int((self.total_iterations - self.current_iteration) *
                            delta_time / self.current_iteration)))

        percent = round(
            100 * float(self.current_iteration) / float(self.total_iterations),
            1)

        if self.current_iteration in self.show_at:
            self.task_label.configure(
                text=self.task +
                ' - {0} % - time left: {1} '.format(percent, time_left))
            if self.elements:
                self.element_label.configure(
                    text=self.elements[self.current_iteration - 1])

            self.progress.set(percent)
Example #27
0
class ErlangCT:
    def __init__(self, f_path):
        self.root = Tk()
        self.root.title("P2: Erlang-C Calculator")

        # excel file path
        self.f_path = f_path

        # member variables
        self.num_servers = 0  # result: number of servers
        self.ew = 0.0  # result: expected waiting time
        self.en = 0.0  # result: expected number packets in system
        self.ens = 0.0  # result: expected number of busy servers
        self.alpha = 0.0  # input: max waiting time
        self.l = 0.0  # input: lambda
        self.u = 0.0  # input: mu

        # text fields and validation for each variable
        self.alpha_entry = Entry(self.root)
        self.l_entry = Entry(self.root)
        self.u_entry = Entry(self.root)

        # text field labels
        self.alpha_label = Label(self.root,
                                 text="Waiting Time Should Not Exceed: ")
        self.l_label = Label(self.root, text="Desired Arrival Rate (lambda): ")
        self.u_label = Label(self.root, text="Desired Service Rate (mu): ")

        # calcualte button
        self.calculate_button = Button(
            self.root,
            text="Calculate",
            command=lambda: self.update("calculate"))
        self.main_menu_button = Button(
            self.root,
            text="Main Menu",
            command=lambda: self.update("main-menu"))

        # initialize result text field
        self.num_servers_result = IntVar()
        self.num_servers_result.set(self.num_servers)
        self.ew_result = DoubleVar()
        self.ew_result.set(self.ew)
        self.en_result = DoubleVar()
        self.en_result.set(self.en)
        self.ens_result = DoubleVar()
        self.ens_result.set(self.en)

        # result text field labels
        self.num_servers_text_label = Label(self.root,
                                            text="Number of Servers Required:")
        self.num_servers_result_label = Label(
            self.root, textvariable=self.num_servers_result)
        self.es_text_label = Label(self.root, text="Expected Waiting Time:")
        self.ew_result_label = Label(self.root, textvariable=self.ew_result)
        self.en_text_label = Label(self.root,
                                   text="Expected Number Packets in System:")
        self.en_result_label = Label(self.root, textvariable=self.en_result)
        self.ens_text_label = Label(self.root,
                                    text="Expected Number of Busy Servers:")
        self.ens_result_label = Label(self.root, textvariable=self.ens_result)

        # Calculator Layout
        self.alpha_label.grid(row=1, column=0, columnspan=3, sticky=W)
        self.alpha_entry.grid(row=1, column=4, columnspan=1, sticky=E)
        self.l_label.grid(row=2, column=0, columnspan=3, sticky=W)
        self.l_entry.grid(row=2, column=4, columnspan=1, sticky=E)
        self.u_label.grid(row=3, column=0, columnspan=3, sticky=W)
        self.u_entry.grid(row=3, column=4, columnspan=1, sticky=E)
        self.calculate_button.grid(row=4, column=0)
        self.num_servers_text_label.grid(row=5, column=0, sticky=W)
        self.num_servers_result_label.grid(row=5,
                                           column=3,
                                           columnspan=2,
                                           sticky=E)
        self.es_text_label.grid(row=6, column=0, sticky=W)
        self.ew_result_label.grid(row=6, column=3, columnspan=2, sticky=E)
        self.en_text_label.grid(row=7, column=0, sticky=W)
        self.en_result_label.grid(row=7, column=3, columnspan=2, sticky=E)
        self.ens_text_label.grid(row=8, column=0, sticky=W)
        self.ens_result_label.grid(row=8, column=3, columnspan=2, sticky=E)
        self.main_menu_button.grid(row=9, column=0)

    def update(self, method):
        if method == "calculate":
            self.alpha = float(self.alpha_entry.get())
            self.l = float(self.l_entry.get())
            self.u = float(self.u_entry.get())

            result = erlang_c_time(self.l, self.u, self.alpha)
            self.num_servers = result['c']
            self.ew = result['ew']
            self.en = result['en']
            self.ens = result['ens']
            self.num_servers_result.set(self.num_servers)
            self.ew_result.set(self.ew)
            self.en_result.set(self.en)
            self.ens_result.set(self.ens)

            self.write_to_excel()

        elif method == "main-menu":
            self.root.destroy()
            from main_menu import MainMenu
            m_menu = MainMenu(self.f_path)
            m_menu.root.mainloop()

        else:  # reset
            self.num_servers = 0

    def write_to_excel(self):
        wb = load_workbook(self.f_path)
        ws = wb["Part 2"]
        data = [["Inputs", "Values", "Results", "Values"],
                [
                    "Max P(wait)", "", "Number of Servers",
                    str(self.num_servers)
                ], ["Max E(w)",
                    str(self.alpha), "E(S)",
                    str(self.ew)],
                ["Arrival Rate",
                 str(self.l), "E(N)",
                 str(self.en)], ["Service Rate",
                                 str(self.u), "", ""]]
        i = 1
        for v in data:
            j = 1
            for e in v:
                c = ws.cell(row=i, column=j)
                c.value = e
                j += 1
            i += 1

        wb.save(self.f_path)
Example #28
0
class HOPSFitsWindow(HOPSWidget):
    def __init__(self,
                 window,
                 input=None,
                 input_name=None,
                 input_options=None,
                 figsize=None,
                 show_nav=False,
                 show_controls=False,
                 show_axes=False,
                 subplots_adjust=None,
                 dwmax=8.0,
                 dhmax=8.0):

        widget = Frame(window.main_frame)

        self.show_axes = show_axes

        if figsize:
            try:
                wpcent, hpcent, wmax, hmax, ratio, = figsize
                wmax, hmax = dwmax, dhmax
                w = min(wpcent * window.log.plt2screen_w, wmax)
                h = min(hpcent * window.log.plt2screen_h, hmax)
                if h * ratio < w:
                    w = h * ratio
                else:
                    h = w / ratio
            except:
                w, h = figsize
            self.figure = matplotlib.figure.Figure(figsize=(w, h))
        else:
            self.figure = matplotlib.figure.Figure()
        self.figure.patch.set_facecolor('white')
        self.canvas = FigureCanvasTkAgg(self.figure, widget)

        self.ax = self.figure.add_subplot(111)
        self.ax.tick_params(axis='y', rotation=90)

        if not self.show_axes:
            self.ax.axis('off')
            self.figure.subplots_adjust(left=0.01,
                                        right=0.99,
                                        bottom=0.01,
                                        top=0.99)

        if subplots_adjust:
            self.figure.subplots_adjust(left=subplots_adjust[0],
                                        right=subplots_adjust[1],
                                        bottom=subplots_adjust[2],
                                        top=subplots_adjust[3])

        self.data = None
        self.mean = 0
        self.std = 0
        self.image = None
        self.sqrt_vmin = DoubleVar(widget, value=0)
        self.vmin = IntVar(widget, value=0)
        self.sqrt_vmax = DoubleVar(widget, value=10000)
        self.vmax = IntVar(widget, value=10000)
        self.gamma = DoubleVar(widget, value=0)
        self.flip = IntVar(widget, value=0)
        self.mirror = IntVar(widget, value=0)
        self.white_sky = IntVar(widget, value=0)

        if input_name:
            if len(input_name) > 50:
                split = [
                    input_name[i:i + 50]
                    for i in range(0, len(input_name), 50)
                ]
                input_name = '\n'.join(split)

        self.fits_name = StringVar(widget, value=input_name)
        self.fits_name_label = Label(widget, textvar=self.fits_name)

        # extra widgets

        control_frame = Frame(widget)
        self.control_frame = control_frame

        self.info_label = Label(
            control_frame,
            text=
            'Scroll up/down to zoom in/out. Click & drag to move the image.')

        self.mouse_data = StringVar(control_frame, value=' ')
        self.mouse_data_label = Label(control_frame, textvar=self.mouse_data)

        self.black_entry = Scale(control_frame,
                                 resolution=0.1,
                                 variable=self.sqrt_vmin,
                                 orient=HORIZONTAL,
                                 showvalue=False)
        self.black_entry.bind("<B1-Motion>", self.contrast)
        self.black_entry.bind("<ButtonRelease-1>", self.contrast)
        self.black_entry_label_0 = Label(control_frame,
                                         text='Minimum = ',
                                         anchor=E)
        self.black_entry_label = Label(control_frame,
                                       textvar=self.vmin,
                                       anchor=W)
        self.black_entry['from_'] = 1
        self.black_entry['to'] = 1000

        self.white_entry = Scale(control_frame,
                                 resolution=0.1,
                                 variable=self.sqrt_vmax,
                                 orient=HORIZONTAL,
                                 showvalue=False)
        self.white_entry.bind("<B1-Motion>", self.contrast)
        self.white_entry.bind("<ButtonRelease-1>", self.contrast)
        self.white_entry_label_0 = Label(control_frame,
                                         text='Maximum = ',
                                         anchor=E)
        self.white_entry_label = Label(control_frame,
                                       textvar=self.vmax,
                                       anchor=W)
        self.white_entry['from_'] = 1
        self.white_entry['to'] = 1000

        self.gamma_entry = Scale(control_frame,
                                 resolution=0.001,
                                 variable=self.gamma,
                                 orient=HORIZONTAL,
                                 showvalue=False)
        self.gamma_entry.bind("<B1-Motion>", self.contrast)
        self.gamma_entry.bind("<ButtonRelease-1>", self.contrast)
        self.gamma_entry_label_0 = Label(control_frame,
                                         text='Stretch factor = ',
                                         anchor=E)
        self.gamma_entry_label = Label(control_frame,
                                       textvar=self.gamma,
                                       anchor=W)
        self.gamma_entry['from_'] = 0
        self.gamma_entry['to'] = 1

        self.flip_button = Checkbutton(control_frame,
                                       text='Flip',
                                       variable=self.flip,
                                       command=self.flip_fov)
        self.mirror_button = Checkbutton(control_frame,
                                         text='Mirror',
                                         variable=self.mirror,
                                         command=self.mirror_fov)
        self.reverse_color_button = Checkbutton(control_frame,
                                                text='White Sky',
                                                variable=self.white_sky,
                                                command=self.reverse_color)
        self.reset_button = Button(control_frame,
                                   text='RESET',
                                   command=self.reset)

        self.info_label.grid(row=1, column=1, columnspan=4)
        self.mouse_data_label.grid(row=2, column=1, columnspan=4)
        self.black_entry_label_0.grid(row=3, column=1, columnspan=2)
        self.black_entry_label.grid(row=3, column=3)
        self.black_entry.grid(row=4,
                              column=1,
                              columnspan=4,
                              sticky=N + S + E + W)
        self.white_entry_label_0.grid(row=5, column=1, columnspan=2)
        self.white_entry_label.grid(row=5, column=3)
        self.white_entry.grid(row=6,
                              column=1,
                              columnspan=4,
                              sticky=N + S + E + W)
        self.gamma_entry_label_0.grid(row=7, column=1, columnspan=2)
        self.gamma_entry_label.grid(row=7, column=3)
        self.gamma_entry.grid(row=8,
                              column=1,
                              columnspan=4,
                              sticky=N + S + E + W)
        self.reset_button.grid(row=9, column=1)
        self.flip_button.grid(row=9, column=2)
        self.mirror_button.grid(row=9, column=3)
        self.reverse_color_button.grid(row=9, column=4)
        Label(control_frame, text=' ').grid(row=10, column=1, columnspan=4)

        self.picked = False

        if input:
            self.load_fits(input, input_name, input_options)

        self.canvas.get_tk_widget().pack(side=TOP)
        if show_nav:
            toolbar = NavigationToolbar2Tk(self.canvas, self.widget)
            toolbar.pack(side=BOTTOM)
        self.fits_name_label.pack()
        if show_controls:
            control_frame.pack()
            self.canvas.callbacks.connect('scroll_event', self.zoom)
            self.canvas.callbacks.connect('motion_notify_event', self.move)
            self.canvas.callbacks.connect('button_press_event', self.pick)
            self.canvas.callbacks.connect('button_release_event', self.pick)

        HOPSWidget.__init__(self, window, widget, 'FitsWindow')

    def load_fits(self, input, input_name=None, input_options=None, draw=True):
        if isinstance(input, str):
            fits = get_fits_data(input)
            input_name = os.path.split(input)[1]
        elif isinstance(input, pf.ImageHDU) or isinstance(
                input, pf.PrimaryHDU) or isinstance(input, pf.CompImageHDU):
            fits = [input]
        else:
            raise RuntimeError('Invalid input ', type(input))

        if input_name:
            if len(input_name) > 50:
                split = [
                    input_name[i:i + 50]
                    for i in range(0, len(input_name), 50)
                ]
                input_name = '\n'.join(split)

        self.fits_name.set(input_name)

        self.data = fits[0].data

        try:
            self.mean = fits[0].header[self.window.log.mean_key]
            self.std = fits[0].header[self.window.log.std_key]
        except:
            self.mean = np.median(fits[0].data)
            self.std = plc.mad(fits[0].data) * 1.5

        self.black_entry['from_'] = np.sqrt(max(0, np.min(self.data)))
        self.black_entry['to'] = np.sqrt(np.max(self.data))

        self.white_entry['from_'] = np.sqrt(max(0, np.min(self.data)))
        self.white_entry['to'] = np.sqrt(np.max(self.data))

        self.ax.cla()
        if not self.show_axes:
            self.ax.axis('off')
        self.ax.tick_params(axis='y', rotation=90)

        self.vmin.set(
            max(1, int(self.mean + self.window.log.frame_low_std * self.std)))
        self.vmax.set(
            max(1,
                int(self.mean + self.window.log.frame_upper_std * self.std)))
        self.gamma.set(0)

        if input_options:
            if input_options[0] != 'auto':
                self.vmin.set(input_options[0])
            if input_options[1] != 'auto':
                self.vmax.set(input_options[1])
            self.gamma.set(input_options[2])
            self.flip.set(input_options[3])
            self.mirror.set(input_options[4])
            self.white_sky.set(input_options[5])

        self.sqrt_vmin.set(np.sqrt(self.vmin.get()))
        self.sqrt_vmax.set(np.sqrt(self.vmax.get()))

        self.image = self.ax.imshow(self.data**(10**-self.gamma.get()),
                                    origin='lower',
                                    extent=(0, len(self.data[0]), 0,
                                            len(self.data)),
                                    cmap=Greys,
                                    vmin=self.vmin.get(),
                                    vmax=self.vmax.get())
        if self.white_sky.get():
            self.image.set_cmap(Greys)
        else:
            self.image.set_cmap(Greys_r)

        if self.flip.get():
            self.ax.set_ylim(len(self.data) + 5, 0)
        else:
            self.ax.set_ylim(0, len(self.data) + 5)

        if self.mirror.get():
            self.ax.set_xlim(len(self.data[0]) + 5, 0)
        else:
            self.ax.set_xlim(0, len(self.data[0]) + 5)

        if draw:
            self.draw()

    def reverse_color(self):
        if self.white_sky.get():
            self.image.set_cmap(Greys)
        else:
            self.image.set_cmap(Greys_r)

        self.draw()

    def flip_fov(self):
        lims = self.ax.get_ylim()
        if self.flip.get():
            self.ax.set_ylim(max(lims), min(lims))
        else:
            self.ax.set_ylim(min(lims), max(lims))
        self.draw()

    def mirror_fov(self):
        lims = self.ax.get_xlim()
        if self.mirror.get():
            self.ax.set_xlim(max(lims), min(lims))
        else:
            self.ax.set_xlim(min(lims), max(lims))
        self.draw()

    def contrast(self, event):

        if self.sqrt_vmin.get() >= self.sqrt_vmax.get():
            self.sqrt_vmin.set(self.sqrt_vmax.get() - 1)

        self.vmin.set(int(self.sqrt_vmin.get()**2))
        self.vmax.set(int(self.sqrt_vmax.get()**2))

        self.image.set_data(np.maximum(0, self.data)**(10**-self.gamma.get()))

        self.image.set_clim(self.vmin.get()**(10**-self.gamma.get()),
                            self.vmax.get()**(10**-self.gamma.get()))
        self.draw()

    def get_fov_options(self):
        return [
            self.vmin.get(),
            self.vmax.get(),
            self.gamma.get(),
            self.flip.get(),
            self.mirror.get(),
            self.white_sky.get()
        ]

    def pick(self, event):

        if isinstance(event, matplotlib.backend_bases.MouseEvent):

            if event.inaxes is None:
                pass

            elif event.name == 'button_press_event':

                self.picked = (event.xdata, event.ydata)

            elif event.name == 'button_release_event':

                self.picked = False

    def move(self, event):

        if isinstance(event, matplotlib.backend_bases.MouseEvent):

            if event.inaxes is None:
                pass

            elif event.name == 'motion_notify_event':

                try:
                    self.mouse_data.set(
                        'Mouse on: x={0:.2f}, y={1:.2f}, counts={2:.2f}'.
                        format(event.xdata, event.ydata,
                               self.data[int(event.ydata),
                                         int(event.xdata)]))
                except:
                    self.mouse_data.set(
                        'Mouse on: x={0:.2f}, y={1:.2f}, counts={2}'.format(
                            event.xdata, event.ydata, '-'))

                if self.picked:

                    dx = event.xdata - self.picked[0]
                    dy = event.ydata - self.picked[1]

                    self.ax.set_xlim(self.ax.get_xlim()[0] - dx,
                                     self.ax.get_xlim()[1] - dx)
                    self.ax.set_ylim(self.ax.get_ylim()[0] - dy,
                                     self.ax.get_ylim()[1] - dy)

                    self.draw()

    def zoom(self, event):

        if isinstance(event, matplotlib.backend_bases.MouseEvent):

            if event.inaxes is None:
                pass

            elif event.name == 'scroll_event':

                zoom_factor = 1.2
                scale_factor = 1.0

                if event.button == 'up':
                    scale_factor = 1 / zoom_factor
                elif event.button == 'down':
                    scale_factor = zoom_factor

                xdata = event.xdata
                ydata = event.ydata

                cur_xlim = self.ax.get_xlim()
                cur_ylim = self.ax.get_ylim()

                cur_xrange = (cur_xlim[1] - cur_xlim[0])
                cur_yrange = (cur_ylim[1] - cur_ylim[0])

                new_xrange = cur_xrange * scale_factor
                new_yrange = cur_yrange * scale_factor

                new_xmin = xdata - new_xrange * (xdata -
                                                 cur_xlim[0]) / cur_xrange
                new_ymin = ydata - new_yrange * (ydata -
                                                 cur_ylim[0]) / cur_yrange

                self.ax.set_xlim([new_xmin, new_xmin + new_xrange])
                self.ax.set_ylim([new_ymin, new_ymin + new_yrange])

                self.draw()

    def reset(self):

        self.ax.set_xlim(0, len(self.data[0]) + 5)
        self.ax.set_ylim(0, len(self.data) + 5)

        if self.flip.get():
            self.ax.set_ylim(self.ax.get_ylim()[1], self.ax.get_ylim()[0])

        if self.mirror.get():
            self.ax.set_xlim(self.ax.get_xlim()[1], self.ax.get_xlim()[0])

        self.vmin.set(
            max(1, int(self.mean + self.window.log.frame_low_std * self.std)))
        self.sqrt_vmin.set(np.sqrt(self.vmin.get()))
        self.vmax.set(
            max(1,
                int(self.mean + self.window.log.frame_upper_std * self.std)))
        self.sqrt_vmax.set(np.sqrt(self.vmax.get()))

        self.gamma.set(0)

        self.image.set_data(np.maximum(0, self.data)**(10**-self.gamma.get()))

        self.image.set_clim(self.vmin.get()**(10**-self.gamma.get()),
                            self.vmax.get()**(10**-self.gamma.get()))
        self.draw()

    def draw(self, update_level=1):
        self.canvas.draw()
        if update_level == 0:
            pass
        elif update_level == 1:
            self.window.update_idletasks()
        elif update_level == 2:
            self.window.update()

    def disable(self):
        for child in self.widget.winfo_children():
            try:
                child.configure(state='disable')
            except:
                pass

    def activate(self):
        for child in self.widget.winfo_children():
            try:
                child.configure(state='active')
            except:
                pass
Example #29
0
class MyApp(Tk):
    """
    This class serves as a central control.
    Where are all process are launched and variables are set and shared.
    """

    __title__ = "Senior"

    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        container = Frame(self)
        container.grid()

        self.serial = SerialComm()

        self.frames = {}
        self.q = LifoQueue()
        self.eye_tracker = EyeTracker(self.q)

        self.variables = {}

        self.fps = IntVar()
        self.fps.set(20)

        self.temp = IntVar()
        self.temp.set(20)
        self.temp.trace("w", self.send_command)
        self.variables[self.temp.__str__()] = 't', self.temp

        self.temp_current = StringVar()
        self.temp_current.set('Temperature')

        self.tts = StringVar()
        self.tts.set('Type and Play')

        self.temp_offset = IntVar()
        self.temp_offset.set(5)
        self.temp_offset.trace("w", self.send_command)
        self.variables[self.temp_offset.__str__()] = 'o', self.temp_offset

        self.samples = 9

        self.window = IntVar()
        self.window.trace("w", self.send_command)
        self.variables[self.window.__str__()] = 'w', self.window

        self.mouse_control = BooleanVar()
        self.mouse_control.set(False)

        self.talk = BooleanVar()
        self.talk.set(True)

        self.alarm = BooleanVar()
        self.alarm.set(False)
        self.alarm.trace("w", self.send_command)
        self.variables[self.alarm.__str__()] = 'a', self.alarm

        self.light = BooleanVar()
        self.light.set(False)
        self.light.trace("w", self.send_command)
        self.variables[self.light.__str__()] = 'l', self.light

        self.heater = BooleanVar()
        self.heater.set(False)
        self.heater.trace("w", self.send_command)
        self.variables[self.heater.__str__()] = 'h', self.heater

        self.ac = BooleanVar()
        self.ac.set(False)
        self.ac.trace("w", self.send_command)
        self.variables[self.ac.__str__()] = 'f', self.ac

        self.move = BooleanVar()
        self.move.set(False)

        self.w, self.h = pyautogui.size()

        self.hor_div = DoubleVar()
        self.hor_div.set(5)
        self.hor_div.trace("w", self.send_command)
        self.variables[self.hor_div.__str__()] = 'hor', self.hor_div

        self.ver_div = DoubleVar()
        self.ver_div.set(5)
        self.ver_div.trace("w", self.send_command)
        self.variables[self.ver_div.__str__()] = 'ver', self.ver_div

        self.mouse_directions = []

        self.mouse = MouseAndSpeech(self)
        self.t = Thread(target=self.mouse.process)
        self.t.start()

        self.frame = None
        self.draw = False

        frame = Preview(container, self)
        self.frames[Preview] = frame
        frame.grid(row=0, column=1, sticky="nsew", rowspan=100)
        self.current_frame = frame

        frame = Settings(container, self)
        self.frames[Settings] = frame
        frame.grid(row=0, column=0, sticky="nsew", pady=10, padx=10)
        frame.grid_remove()

        frame = Applications(container, self)
        self.frames[Applications] = frame
        frame.grid(row=0, column=0, sticky="nsew", pady=10, padx=10)
        frame.grid_remove()

        # Menu Bar
        menu = MyMenu(self)
        self.config(menu=menu)

        Tk.iconbitmap(self, default=resource_path('icon.ico'))
        Tk.wm_title(self, "Senior")
        w = (self.winfo_screenwidth() - self.eye_tracker.window_size) // 2
        self.geometry('+{}+{}'.format(w, 0))
        self.protocol("WM_DELETE_WINDOW", lambda: self.close())

    def show_frame(self, cont):
        """
        This method is used to switch betwen views.
        """
        if self.current_frame is not None:
            self.current_frame.grid_remove()
        frame = self.frames[cont]
        frame.grid()
        self.current_frame = frame

        if cont is Applications:
            frame.button_alarm.focus()

    def send_command(self, widget, *args):
        """
        This method send data to the Arduino whenever a button is clicked.
        """
        w = self.variables[widget]
        try:
            indicator = w[0]
            value = str(int(w[1].get()))
            if indicator == 'f' and value == '1':
                self.heater.set(False)
                self.serial.send_serial('h0')
            elif indicator == 'h' and value == '1':
                self.ac.set(False)
                self.serial.send_serial('f0')
            elif indicator == 't':
                self.heater.set(False)
                self.ac.set(False)

            s = indicator + value
            self.serial.send_serial(s)

            if len(value) > 0:
                value = float(w[1].get())
                if indicator in ['ver', 'hor']:
                    x_offset = self.ver_div.get()
                    y_offset = self.hor_div.get()
                    if indicator == 'ver':
                        y_offset = value * (self.h // 100)
                    elif indicator == 'hor':
                        x_offset = value * (self.w // 100)

                    self.mouse_directions = [(-x_offset, -y_offset),
                                             (0, -y_offset),
                                             (x_offset, -y_offset),
                                             (-x_offset, 0), 0, (x_offset, 0),
                                             (-x_offset, y_offset),
                                             (0, y_offset),
                                             (x_offset, y_offset), 0]
        except:
            pass

    def close(self):
        """
        Method used to to close the program orderly so no threads are left hanging.
        """

        print(self.__title__)
        while self.mouse.isTalking:
            print('Is Talking')

        self.eye_tracker.video_capture.release()
        clear_queue(self.q)
        self.q.put(False)
        self.q.join()
        self.t.join()
        self.destroy()
Example #30
0
    def __init__(self, master, par=False):
        """
        GUI for selecting default parameters - will write parameters to file \
        of users choosing.

        :type master: Tk
        :param master: Tkinter window
        :type par: EQcorrscanParameters
        :param par: Default parameters to start-up with.
        """
        from tkinter import Label, Button, Entry, DoubleVar, StringVar, IntVar
        from tkinter import BooleanVar, OptionMenu, Checkbutton
        import tkMessageBox
        from eqcorrscan.utils import parameters
        from obspy import UTCDateTime
        import warnings

        # Set the default par, only if they don't already exist.
        if not par:
            par = parameters.EQcorrscanParameters([''], 2, 10, 4, 100, 2,
                                                  '1900-01-01', '2300-01-01',
                                                  '', 'seishub', 4, False, '',
                                                  'jpg', False, 8, 'MAD', 6)
        # Callback functions for all variables (ugly)

        def update_template_names(*args):
            par.template_names = [name.strip() for name in
                                  template_names.get().split(',')]
            template_names.set(', '.join(par.template_names))

        def update_lowcut(*args):
            par.lowcut = lowcut.get()
            lowcut.set(par.lowcut)

        def update_highcut(*args):
            par.highcut = highcut.get()
            if par.highcut >= 0.5 * par.samp_rate:
                msg = ('Highcut must be less than the Nyquist, setting to ' +
                       str((par.samp_rate / 2.0) - 1))
                tkMessageBox.showwarning(title="Nyquist error",
                                         message=msg)
                par.highcut = (par.samp_rate / 2.0) - 1
            highcut.set(par.highcut)

        def update_filt_order(*args):
            par.filt_order = filt_order.get()
            filt_order.set(par.filt_order)

        def update_samp_rate(*args):
            par.samp_rate = samp_rate.get()
            if par.highcut >= 0.5 * par.samp_rate:
                msg = ('Highcut must be less than the Nyquist, setting to ' +
                       str((par.samp_rate / 2.0) - 1))
                tkMessageBox.showwarning(title="Nyquist error",
                                         message=msg)
                par.highcut = (par.samp_rate / 2.0) - 1
                highcut.set(par.highcut)
            samp_rate.set(par.samp_rate)

        def update_debug(*args):
            par.debug = debug.get()
            debug.set(par.debug)

        def update_startdate(*args):
            par.startdate = UTCDateTime(startdate.get())
            startdate.set(str(par.startdate))

        def update_enddate(*args):
            par.enddate = UTCDateTime(enddate.get())
            enddate.set(str(par.enddate))

        def update_archive(*args):
            par.archive = archive.get()
            archive.set(par.archive)

        def update_arc_type(*args):
            par.arc_type = arc_type.get()
            arc_type.set(par.arc_type)

        def update_cores(*args):
            par.cores = cores.get()
            cores.set(par.cores)

        def update_plotvar(*args):
            par.plotvar = plotvar.get()
            plotvar.set(par.plotvar)

        def update_plot_format(*args):
            par.plot_format = plot_format.get()
            plot_format.set(par.plot_format)

        def update_tempdir(*args):
            par.tempdir = tempdir.get()
            tempdir.set(par.tempdir)

        def update_threshold(*args):
            par.threshold = threshold.get()
            threshold.set(par.threshold)

        def update_threshold_type(*args):
            par.threshold_type = threshold_type.get()
            threshold_type.set(par.threshold_type)

        def update_plotdir(*args):
            par.plotdir = plotdir.get()
            plotdir.set(par.plotdir)

        def update_trigger_interval(*args):
            par.trigger_interval = trigger_interval.get()
            trigger_interval.set(par.trigger_interval)
        # Set some grid parameters
        nrows = 25
        ncolumns = 3
        self.master = master
        master.title("EQcorrscan parameter setup")
        self.label = Label(master, text="Alpha GUI for default setup")
        self.label.grid(column=0, columnspan=ncolumns, row=0)

        # Set up parameter input
        self.t_names_label = Label(master, text="Template names", anchor='e')
        self.t_names_label.grid(column=0, row=1, sticky='e')
        template_names = StringVar()
        template_names.set(', '.join(par.template_names))
        self.t_names_box = Entry(master, bd=2, textvariable=template_names)
        self.t_names_box.grid(column=1, row=1)
        template_names.trace("w", update_template_names)
        self.t_names_lookup = Button(master, text="Lookup",
                                     command=lambda: self.get_template_names(par))
        self.t_names_lookup.grid(column=2, row=1)

        self.lowcut_label = Label(master, text="Lowcut (Hz)", anchor='e')
        self.lowcut_label.grid(column=0, row=2, sticky='e')
        lowcut = DoubleVar()
        lowcut.set(par.lowcut)
        self.lowcut_box = Entry(master, bd=2, textvariable=lowcut)
        self.lowcut_box.grid(column=1, row=2)
        lowcut.trace("w", update_lowcut)

        self.highcut_label = Label(master, text="Highcut (Hz)", anchor='e')
        self.highcut_label.grid(column=0, row=3, sticky='e')
        highcut = DoubleVar()
        highcut.set(par.highcut)
        self.highcut_box = Entry(master, bd=2, textvariable=highcut)
        self.highcut_box.grid(column=1, row=3)
        highcut.trace("w", update_highcut)

        self.filt_order_label = Label(master, text="Filter order")
        self.filt_order_label.grid(column=0, row=4, sticky='e')
        filt_order = DoubleVar()
        filt_order.set(par.filt_order)
        self.filt_order_box = Entry(master, bd=2, textvariable=filt_order)
        self.filt_order_box.grid(column=1, row=4)
        filt_order.trace("w", update_filt_order)

        self.samp_rate_label = Label(master, text="Sample rate (Hz)")
        self.samp_rate_label.grid(column=0, row=5, sticky='e')
        samp_rate = DoubleVar()
        samp_rate.set(par.samp_rate)
        self.samp_rate_box = Entry(master, bd=2, textvariable=samp_rate)
        self.samp_rate_box.grid(column=1, row=5)
        samp_rate.trace("w", update_samp_rate)

        self.debug_label = Label(master, text="Debug")
        self.debug_label.grid(column=0, row=6, sticky='e')
        debug = IntVar()
        debug.set(par.debug)
        self.debug_box = Entry(master, bd=2, textvariable=debug)
        self.debug_box.grid(column=1, row=6)
        debug.trace("w", update_debug)

        self.startdate_label = Label(master, text="Start date (yyyy-mm-dd)")
        self.startdate_label.grid(column=0, row=6, sticky='e')
        startdate = StringVar()
        startdate.set(par.startdate)
        self.startdate_box = Entry(master, bd=2, textvariable=startdate)
        self.startdate_box.grid(column=1, row=6)
        startdate.trace("w", update_startdate)

        self.enddate_label = Label(master, text="End date (yyyy-mm-dd)")
        self.enddate_label.grid(column=0, row=8, sticky='e')
        enddate = StringVar()
        enddate.set(par.enddate)
        self.enddate_box = Entry(master, bd=2, textvariable=enddate)
        self.enddate_box.grid(column=1, row=8)
        enddate.trace("w", update_enddate)

        self.archive_label = Label(master, text="Archive")
        self.archive_label.grid(column=0, row=9, sticky='e')
        archive = StringVar()
        archive.set(par.archive)
        self.archive_box = Entry(master, bd=2, textvariable=archive)
        self.archive_box.grid(column=1, row=9)
        archive.trace("w", update_archive)
        self.archive_lookup = Button(master, text="Lookup",
                                     command=lambda: self.get_archive(par))
        self.archive_lookup.grid(column=2, row=9)


        self.arc_type_label = Label(master, text="Archive type")
        self.arc_type_label.grid(column=0, row=10, sticky='e')
        arc_type = StringVar()
        arc_type.set(par.arc_type)
        self.arc_type_box = OptionMenu(master, arc_type,
                                       "seishub", "fdsn", "day_vols")
        self.arc_type_box.grid(column=1, row=10, sticky='w,e')
        arc_type.trace("w", update_arc_type)

        self.cores_label = Label(master, text="Number of cores")
        self.cores_label.grid(column=0, row=11, sticky='e')
        cores = IntVar()
        cores.set(par.cores)
        self.cores_box = Entry(master, bd=2, textvariable=cores)
        self.cores_box.grid(column=1, row=11)
        cores.trace("w", update_cores)

        self.plotvar_label = Label(master, text="Plotting on/off")
        self.plotvar_label.grid(column=0, row=12, sticky='e')
        plotvar = BooleanVar()
        plotvar.set(par.plotvar)
        self.plotvar_box = Checkbutton(master, text='Plot on', var=plotvar,
                                       onvalue=True, offvalue=False)
        self.plotvar_box.grid(column=1, row=12)
        plotvar.trace("w", update_plotvar)

        self.plotdir_label = Label(master, text="Plot directory")
        self.plotdir_label.grid(column=0, row=13, sticky='e')
        plotdir = StringVar()
        plotdir.set(par.plotdir)
        self.plotdir_box = Entry(master, bd=2, textvariable=plotdir)
        self.plotdir_box.grid(column=1, row=13)
        plotdir.trace("w", update_plotdir)
        self.plotdir_lookup = Button(master, text="Lookup",
                                     command=lambda: self.get_plotdir(par))
        self.plotdir_lookup.grid(column=2, row=13)

        self.plot_format_label = Label(master, text="Plot format")
        self.plot_format_label.grid(column=0, row=14, sticky='e')
        plot_format = StringVar()
        plot_format.set(par.plot_format)
        self.plot_format_box = OptionMenu(master, plot_format,
                                          "jpg", "eps", "pdf", "png")
        self.plot_format_box.grid(column=1, row=14, sticky='w,e')
        plot_format.trace("w", update_plot_format)

        self.tempdir_label = Label(master, text="Temporary directory")
        self.tempdir_label.grid(column=0, row=15, sticky='e')
        tempdir = StringVar()
        tempdir.set(par.tempdir)
        self.tempdir_box = Entry(master, bd=2, textvariable=tempdir)
        self.tempdir_box.grid(column=1, row=15)
        tempdir.trace("w", update_tempdir)
        self.tempdir_lookup = Button(master, text="Lookup",
                                     command=lambda: self.get_tempdir(par))
        self.tempdir_lookup.grid(column=2, row=15)

        self.threshold_label = Label(master, text="Threshold")
        self.threshold_label.grid(column=0, row=16, sticky='e')
        threshold = DoubleVar()
        threshold.set(par.threshold)
        self.threshold_box = Entry(master, bd=2, textvariable=threshold)
        self.threshold_box.grid(column=1, row=16)
        threshold.trace("w", update_threshold)

        self.threshold_type_label = Label(master, text="Threshold type")
        self.threshold_type_label.grid(column=0, row=17, sticky='e')
        threshold_type = StringVar()
        threshold_type.set(par.threshold_type)
        self.threshold_type_box = OptionMenu(master, threshold_type,
                                             "MAD", "absolute", "av_chan_corr")
        self.threshold_type_box.grid(column=1, row=17, sticky='w,e')
        threshold_type.trace("w", update_threshold_type)

        self.trigger_interval_label = Label(master,
                                            text="Minimum trigger " +
                                            "interval (s)")
        self.trigger_interval_label.grid(column=0, row=18, sticky='e')
        trigger_interval = DoubleVar()
        trigger_interval.set(par.trigger_interval)
        self.trigger_interval_box = Entry(master, bd=2,
                                          textvariable=trigger_interval)
        self.trigger_interval_box.grid(column=1, row=18)
        trigger_interval.trace("w", update_trigger_interval)

        # End of user editable section, now we have read/write buttons
        self.read_button = Button(master, text="Read parameters",
                                  command=lambda: self.read_par(master))
        self.read_button.grid(column=0, row=nrows-2, sticky='w,e')

        self.write_button = Button(master, text="Write parameters",
                                   command=lambda: self.write_par(par))
        self.write_button.grid(column=1, row=nrows-2, sticky='w,e')
class ErlangB:

    def __init__(self, f_path):
        self.root = Tk()
        self.root.title("P1: Erlang-B Calculator")

        # excel file path
        self.f_path = f_path

        # member variables
        self.num_servers = 0    # result: number of servers
        self.pb_actual = 0.0    # result: actual probability of blocking
        self.pb = 0.0           # input: desired probability of blocking
        self.l = 0.0            # input: lambda
        self.u = 0.0            # input: mu

        # text fields and validation for each variable
        self.pb_entry = Entry(self.root)
        self.l_entry = Entry(self.root)
        self.u_entry = Entry(self.root)

        # text field labels
        self.pb_label = Label(self.root, text="Desired Probability of Blocking: ")
        self.l_label = Label(self.root, text="Desired Arrival Rate (lambda): ")
        self.u_label = Label(self.root, text="Desired Service Rate (mu): ")

        # calcualte button
        self.calculate_button = Button(self.root, text="Calculate", command=lambda: self.update("calculate"))
        self.main_menu_button = Button(self.root, text="Main Menu", command=lambda: self.update("main-menu"))

        # initialize result text field
        self.num_servers_result = IntVar()
        self.num_servers_result.set(self.num_servers)
        self.pb_actual_result = DoubleVar()
        self.pb_actual_result.set(self.pb_actual)

        # result text field labels
        self.num_servers_text_label = Label(self.root, text="Number of Servers Required:")
        self.num_servers_result_label = Label(self.root, textvariable=self.num_servers_result)
        self.pb_actual_text_label = Label(self.root, text="Actual Probability of Blocking:")
        self.pb_actual_result_label = Label(self.root, textvariable=self.pb_actual_result)

        # Calculator Layout
        self.pb_label.grid(row=0, column=0, columnspan=3, sticky=W)
        self.pb_entry.grid(row=0, column=4, columnspan=1, sticky=E)
        self.l_label.grid(row=1, column=0, columnspan=3, sticky=W)
        self.l_entry.grid(row=1, column=4, columnspan=1, sticky=E)
        self.u_label.grid(row=2, column=0, columnspan=3, sticky=W)
        self.u_entry.grid(row=2, column=4, columnspan=1, sticky=E)
        self.calculate_button.grid(row=3, column=0)
        self.num_servers_text_label.grid(row=4, column=0, sticky=W)
        self.num_servers_result_label.grid(row=4, column=3, columnspan=2, sticky=E)
        self.pb_actual_text_label.grid(row=5, column=0, sticky=W)
        self.pb_actual_result_label.grid(row=5, column=3, columnspan=2, sticky=E)
        self.main_menu_button.grid(row=6, column=0)
        
    def update(self, method):
        if method == "calculate":
            self.pb = float(self.pb_entry.get())
            self.l = float(self.l_entry.get())
            self.u = float(self.u_entry.get())

            result = erlang_b(self.pb, self.l, self.u)
            self.num_servers = result['c']
            self.pb_actual = result['pb_actual']
            self.num_servers_result.set(self.num_servers)
            self.pb_actual_result.set(self.pb_actual)

            self.write_to_excel()

        elif method == "main-menu":
            self.root.destroy()
            from main_menu import MainMenu
            m_menu = MainMenu(self.f_path)
            m_menu.root.mainloop()
            
        else: # reset
            self.num_servers = 0
    
    def write_to_excel(self):
        wb = load_workbook(self.f_path)
        ws = wb["Part 1"]
        data = [
            ["Inputs", "Values", "Results", "Values"],
            ["Max P(blocking)", str(self.pb),"Number of Servers", str(self.num_servers)],
            ["Arrival Rate", str(self.l), "P(blocking)", str(self.pb_actual)],
            ["Service Rate", str(self.u),"", ""]
        ]
        i = 1
        for v in data:
            j = 1
            for e in v:
                c = ws.cell(row = i, column = j)
                c.value = e
                j += 1
            i += 1

        wb.save(self.f_path)
Example #32
0
    def __init__(self, root):
        root.title("TP3 - Branch & Bound")

        root.resizable(width=False, height=False)

        # Labels

        res_label = tk.Label(root)
        ft = tkFont.Font(family='Times', size=15)
        res_label["font"] = ft
        res_label["fg"] = "#000"
        res_label["justify"] = "center"
        self.res_label = res_label

        number_of_variables_label = tk.Label(root)
        ft = tkFont.Font(family='Times', size=18)
        number_of_variables_label["font"] = ft
        number_of_variables_label["fg"] = "#333333"
        number_of_variables_label["justify"] = "center"
        number_of_variables_label["text"] = "Var Num"
        number_of_variables_label.grid(row=0, column=0)

        max_weight_label = tk.Label(root)
        ft = tkFont.Font(family='Times', size=18)
        max_weight_label["font"] = ft
        max_weight_label["fg"] = "#333333"
        max_weight_label["justify"] = "center"
        max_weight_label["text"] = "Max W"
        max_weight_label.grid(row=0, column=4)

        # Entries
        num_var = tk.IntVar(root)
        num_var.set(7)
        number_of_variables = tk.Entry(root, textvariable=num_var)
        number_of_variables["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times', size=10)
        number_of_variables["font"] = ft
        number_of_variables["fg"] = "#333333"
        number_of_variables["justify"] = "center"
        number_of_variables.grid(padx=10, row=0, column=1)
        self.number_of_variables = num_var

        max_w_var = tk.IntVar(root)
        max_w_var.set(1)
        max_weight_entry = tk.Entry(root, textvariable=max_w_var)
        max_weight_entry["borderwidth"] = "1px"
        ft = tkFont.Font(family='Times', size=10)
        max_weight_entry["font"] = ft
        max_weight_entry["fg"] = "#333333"
        max_weight_entry["justify"] = "center"
        max_weight_entry.grid(row=0, column=5)
        self.max_weight_entry = max_w_var

        change_var_entries = tk.Button(root)
        change_var_entries["activebackground"] = "#cc0000"
        change_var_entries["activeforeground"] = "#ffffff"
        change_var_entries["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times', size=18)
        change_var_entries["font"] = ft
        change_var_entries["fg"] = "#000"
        change_var_entries["justify"] = "center"
        change_var_entries["text"] = "Change"
        change_var_entries.grid(row=0, column=2)
        change_var_entries[
            "command"] = self.change_num_of_variables_entries_command

        solve_button = tk.Button(root)
        solve_button["activebackground"] = "#cc0000"
        solve_button["activeforeground"] = "#ffffff"
        solve_button["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times', size=18)
        solve_button["font"] = ft
        solve_button["fg"] = "#f00"
        solve_button["justify"] = "center"
        solve_button["text"] = "Search"
        solve_button.grid(row=1, column=0)
        solve_button["command"] = self.solve_button_command

        # init variable entires

        x_label = tk.Label(root)
        ft = tkFont.Font(family='Times', size=15)
        x_label["font"] = ft
        x_label["fg"] = "#000"
        x_label["justify"] = "center"
        x_label["text"] = "Values"
        x_label.grid(row=4, column=0)

        x_label = tk.Label(root)
        ft = tkFont.Font(family='Times', size=15)
        x_label["font"] = ft
        x_label["fg"] = "#000"
        x_label["justify"] = "center"
        x_label["text"] = "Weights"
        x_label.grid(row=5, column=0)

        for i in np.arange(0, int(self.number_of_variables.get()), 1):
            x_label = tk.Label(root)
            ft = tkFont.Font(family='Times', size=15)
            x_label["font"] = ft
            x_label["fg"] = "#000"
            x_label["justify"] = "center"
            x_label["text"] = "x" + str(i + 1)
            x_label.grid(row=3, column=i + 1)

            x_val_var = DoubleVar(root)
            x_val_var.set(0)
            x_value_entry = tk.Entry(root, textvariable=x_val_var)
            x_value_entry["borderwidth"] = "1px"
            ft = tkFont.Font(family='Times', size=10)
            x_value_entry["font"] = ft
            x_value_entry["fg"] = "#333333"
            # x_value_entry['relief'] = "groove"
            x_value_entry["justify"] = "center"
            x_value_entry.grid(row=4, column=i + 1)

            x_w_var = DoubleVar(root)
            x_w_var.set(1)
            x_weight_entry = tk.Entry(root, textvariable=x_w_var)
            x_weight_entry["borderwidth"] = "1px"
            ft = tkFont.Font(family='Times', size=10)
            x_weight_entry["font"] = ft
            x_weight_entry["fg"] = "#333333"
            # x_weight_entry['relief'] = "groove"
            x_weight_entry["justify"] = "center"
            x_weight_entry.grid(row=5, column=i + 1)

            self.variables.append(Item(i, x_val_var, x_w_var))
            self.lvw.append((x_label, x_value_entry, x_weight_entry))

        # default exo values buttons!

        x_label = tk.Label(root)
        ft = tkFont.Font(family='Times', size=15)
        x_label["font"] = ft
        x_label["fg"] = "#000"
        x_label["justify"] = "center"
        x_label["text"] = "Default Values of:"
        x_label.grid(row=6, column=0)

        tp3_button = tk.Button(root)
        tp3_button["activebackground"] = "#cc0000"
        tp3_button["activeforeground"] = "#ffffff"
        tp3_button["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times', size=13)
        tp3_button["font"] = ft
        tp3_button["fg"] = "#000"
        tp3_button["justify"] = "center"
        tp3_button["text"] = "TP3"
        tp3_button.grid(row=6, column=1, pady=10)
        tp3_button["command"] = self.tp3_values_set

        td2_exo5_button = tk.Button(root)
        td2_exo5_button["activebackground"] = "#cc0000"
        td2_exo5_button["activeforeground"] = "#ffffff"
        td2_exo5_button["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times', size=13)
        td2_exo5_button["font"] = ft
        td2_exo5_button["fg"] = "#000"
        td2_exo5_button["justify"] = "center"
        td2_exo5_button["text"] = "TD2EXO5"
        td2_exo5_button.grid(row=6, column=2, pady=10)
        td2_exo5_button["command"] = self.td2_exo5_values_set

        td2_exo7_button = tk.Button(root)
        td2_exo7_button["activebackground"] = "#cc0000"
        td2_exo7_button["activeforeground"] = "#ffffff"
        td2_exo7_button["bg"] = "#f0f0f0"
        ft = tkFont.Font(family='Times', size=13)
        td2_exo7_button["font"] = ft
        td2_exo7_button["fg"] = "#000"
        td2_exo7_button["justify"] = "center"
        td2_exo7_button["text"] = "TD2EXO7"
        td2_exo7_button.grid(row=6, column=3, pady=10)
        td2_exo7_button["command"] = self.td2_exo7_values_set
Example #33
0
class ProcessScreen(Frame):

    progressBarRun = Progressbar
    progressBarStyle = Style
    progressNumber = DoubleVar
    TextProgressProcess = Label
    scanStructObject = scanStruct
    log = logController
    btProcessFinish = Button

    def configureScreen(self):

        self.bind("<Configure>", self.configureWidth)

        self.log = logController()

        self.progressNumber = DoubleVar()
        self.progressBarStyle = Style()
        self.progressBarStyle.theme_use('clam')
        self.progressBarStyle.configure("Horizontal.TProgressbar",
                                        troughcolor='#616161',
                                        background="#34A853",
                                        lightcolor='#34A853',
                                        darkcolor="#34A853")
        self.progressBarRun = Progressbar(self,
                                          style="Horizontal.TProgressbar",
                                          variable=self.progressNumber,
                                          maximum=10)
        self.progressBarRun.pack(fill=X, padx=10, pady=10)

        self.TextProgressProcess = Label(self)
        self.TextProgressProcess["bg"] = "#9E9E9E"
        self.TextProgressProcess["font"] = ("Roboto Black", "20")
        self.TextProgressProcess["fg"] = "white"
        self.TextProgressProcess.pack(padx=10, pady=15, expand=True)

        self.btProcessFinish = Button(self)
        self.btProcessFinish["font"] = ("Roboto Black", "20")
        self.btProcessFinish["fg"] = "white"
        self.btProcessFinish["relief"] = "flat"
        self.btProcessFinish["command"] = self.ProcessFinish

    def configureWidth(self, event):

        self.TextProgressProcess["wraplength"] = event.width - 15

    def executeProcess(self, dirMainExec):

        self.scanStructObject = scanStruct(dirMainExec)

        self.ConfigScan()

        taskExecuteProcess = Thread(target=self.ExecuteScan, args=[])
        taskExecuteProcess.start()

    def ExecuteScan(self):

        executeScanTask = Thread(target=self.scanStructObject.execute, args=[])
        executeScanTask.start()

        while (self.scanStructObject.isExecuteProcess):

            taskUpdProgress = Thread(target=self.updProgressBarRun, args=[])
            taskUpdProgress.start()

            sleep(0.5)

            if (self.progressNumber.get() == 10):

                clearTask = Thread(target=self.ClearProgressBar, args=[])
                clearTask.start()

        if (self.scanStructObject.wasFoundSomething):

            if (len(self.scanStructObject.getApperservers()) > 0):

                self.master.appservers = self.scanStructObject.getApperservers(
                )
            else:

                self.master.appservers = {}
            if (len(self.scanStructObject.getSmartclients()) > 0):

                self.master.smartclients = self.scanStructObject.getSmartclients(
                )
            else:

                self.master.smartclients = {}

            stageTask = Thread(target=self.updExecuteProcess, args=[])
            stageTask.start()

            self.master.resultScreen.clear()
            self.master.resultScreen.ShowInformationResult()

            self.btProcessFinish.pack(fill=X, padx=40, pady=20)

            self.btProcessFinish["bg"] = "#34A853"
            self.btProcessFinish["text"] = "Proximo >"
            self.TextProgressProcess[
                "text"] = "Pronto, agora é só ver os resultados!! :)"
        else:

            self.btProcessFinish.pack(fill=X, padx=40, pady=20)

            self.btProcessFinish["bg"] = "#EA4335"
            self.btProcessFinish["text"] = "< Anterior"
            self.TextProgressProcess[
                "text"] = "Não foi encontrado nada nessa pasta :("

    def updExecuteProcess(self):

        self.TextProgressProcess["text"] = "Gerando Cards do resultado..."
        self.progressNumber.set(10)

    def ClearProgressBar(self):

        self.progressNumber.set(0)

    def updProgressBarRun(self):

        self.progressNumber.set(self.progressNumber.get() + 1)
        self.TextProgressProcess[
            "text"] = self.scanStructObject.textProgressExecute

    def ProcessFinish(self):

        if (self.scanStructObject.wasFoundSomething):

            self.master.gotoResult()
        else:

            self.master.returnToHome()

    def ClearComponent(self):

        self.btProcessFinish.pack_forget()

        self.TextProgressProcess[
            "text"] = "Procurando arquivos da estrutura Protheus..."

        self.ClearProgressBar()

    def ConfigScan(self):

        linha = ''
        StringErro = ''

        try:

            with open('configScan.csv', 'r') as configArqCSV:

                readerArq = reader(configArqCSV, delimiter=';')

                for linha in readerArq:

                    if (linha[0].upper() == 'APPSERVERKEYS'):

                        for appServerKey in linha:

                            if (appServerKey.upper() == 'APPSERVERKEYS'):

                                pass
                            else:

                                self.scanStructObject.addAppServerKey(
                                    appServerKey)
                    if (linha[0].upper() == 'SMARTCLIENTKEYS'):

                        for smartclientKey in linha:

                            if (smartclientKey.upper() == 'SMARTCLIENTKEYS'):

                                pass
                            else:

                                self.scanStructObject.addSmartClientKey(
                                    smartclientKey)
                    if (linha[0].upper() == 'RPONAME'):

                        self.scanStructObject.cNameRPO = linha[1] + ".rpo"

        except Exception as e:

            StringErro += '###########################################################\n'
            StringErro += "Erro no CSVConfig: \t" + str(e) + "\n"
            StringErro += '###########################################################\n'

            self.log.consoleLogAdd(StringErro)
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        
        Home_Button = ttk.Button(self, text = "Home", command = lambda: controller.show_frame(home_module.Home)) # Button to open Home screen
        Home_Button.grid(column = 2, row = 9, sticky = "nwes")
        
        WDB_Button = ttk.Button(self, text = "Watts To dB", command = lambda: controller.show_frame(watts_to_decibels.WDB))# Button to open W to dB screen
        WDB_Button.grid(column = 1, row = 9, sticky = "nwes")
            
        def dB_W(*args):
            try:
                Value = float(Data_In.get())
                Range_Set = str(Range_1.get())
                if Range_Set == 'dBm':
                    dBm.set(Value)
                    dBW.set(Value - 30)
                    dBk.set(Value - 60)
                    mW.set(pow(10, (Value / 10)))
                    W.set(pow(10, (Value / 10)) / 1000)
                    kW.set(pow(10, (Value / 10)) / 1000000)
                if Range_Set == 'dBW':
                    dBm.set(Value + 30)
                    dBW.set(Value)
                    dBk.set(Value - 30)
                    mW.set(pow(10, (Value / 10)) * 1000)
                    W.set(pow(10, (Value / 10)))
                    kW.set(pow(10, (Value / 10)) / 1000)
                if Range_Set == 'dBk':
                    dBm.set(Value + 60)
                    dBW.set(Value + 30)
                    dBk.set(Value)
                    mW.set(pow(10, (Value / 10)) * 1000000)
                    W.set(pow(10, (Value / 10)) * 1000)
                    kW.set(pow(10, (Value / 10)))
                      
            except ValueError:
                dBm.set(0.0)
                dBW.set(0.0)
                dBk.set(0.0)
                mW.set(0.0)
                W.set(0.0)
                kW.set(0.0)   
                
        def dB_range_select(*args):
            Range_Set = str(Range_1.get())
            if Range_Set == 'dBm':
                Range_2.set("mW")
            if Range_Set == 'dBW':
                Range_2.set("W")
            if Range_Set == 'dBk':
                Range_2.set("kW")
    
        Range_1 = StringVar()
        Range_1.set('dBm')
        Range_2 = StringVar()
        Range_2.set('mW')
        Range_Selection = ttk.Combobox(self, textvariable = Range_1, state = 'readonly')
        Range_Selection['values'] = ('dBm', 'dBW', 'dBk')
        Range_Selection.grid(column = 2, row = 1, sticky = "nwes")
        Range_Selection.bind('<<ComboboxSelected>>', dB_range_select)
        
        Data_In = StringVar()
        Data_In.set(0)
        dBm = StringVar()
        dBm.set(0.0)
        dBW = StringVar()
        dBW.set(0.0)
        dBk = StringVar()
        dBk.set(0.0)
        mW = StringVar()
        mW.set(0.0)
        W = StringVar()
        W.set(0.0)
        kW = DoubleVar()
        kW.set(0.0)

        dB_entry = ttk.Entry(self, width = 7, textvariable = Data_In)
        dB_entry.grid(column = 2, row = 2, sticky = "nwes")
        
        ttk.Label(self, textvariable = dBm).grid(column = 2, row = 3, sticky = "nwes")
        ttk.Label(self, textvariable = dBW).grid(column = 2, row = 4, sticky = "nwes")
        ttk.Label(self, textvariable = dBk).grid(column = 2, row = 5, sticky = "nwes")
        ttk.Label(self, textvariable = mW).grid(column = 2, row = 6, sticky = "nwes")
        ttk.Label(self, textvariable = W).grid(column = 2, row = 7, sticky = "nwes")
        ttk.Label(self, textvariable = kW).grid(column = 2, row = 8, sticky = "nwes")
    
        ttk.Button(self, text = "Calculate", command = dB_W).grid(column = 3, row = 9, sticky = "nwes")
        
        ttk.Label(self, text = "Please choose a range :").grid(column = 1, row = 1, sticky = "nwes")
        ttk.Label(self, text = "Please enter a number :").grid(column = 1, row = 2, sticky = "nwes")
        ttk.Label(self, textvariable = Range_1).grid(column = 3, row = 2, sticky = "nwes")
        ttk.Label(self, text = "Is equivalent to :").grid(column = 1, row = 3, sticky = "nwes")
        ttk.Label(self, textvariable = Range_2).grid(column = 3, row = 3, sticky = "nwes")
        
        ttk.Label(self, text = "dBm").grid(column = 3, row = 3, sticky = "nwes")
        ttk.Label(self, text = "dBW").grid(column = 3, row = 4, sticky = "nwes")
        ttk.Label(self, text = "dBk").grid(column = 3, row = 5, sticky = "nwes")
        ttk.Label(self, text = "mW").grid(column = 3, row = 6, sticky = "nwes")
        ttk.Label(self, text = "W").grid(column = 3, row = 7, sticky = "nwes")
        ttk.Label(self, text = "kW").grid(column = 3, row = 8, sticky = "nwes")
    
        for child in DBW.winfo_children(self):

            child.grid_configure(padx = 5, pady = 5)