Example #1
0
class PasswordDialog(Dialog):

    def __init__(self, title, prompt, parent):
        self.prompt = prompt
        Dialog.__init__(self, parent, title)

    def body(self, master):
        from Tkinter import Label
        from Tkinter import Entry
        from Tkinter import Checkbutton
        from Tkinter import IntVar
        from Tkinter import W

        self.checkVar = IntVar()

        Label(master, text=self.prompt).grid(row=0, sticky=W)

        self.e1 = Entry(master)

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

        self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar)
        self.cb.pack()
        self.cb.grid(row=1, columnspan=2, sticky=W)
        self.e1.configure(show='*')

    def apply(self):
        self.result = (self.e1.get(), self.checkVar.get() == 1)
Example #2
0
class encoderface(LabelFrame):

    def __init__(self, x):
        LabelFrame.__init__(self, x)       
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=12)
        self.config(relief=GROOVE)
        self.config(borderwidth=2, padx=5, pady=5)
        self.config(text = "Encoder")
        self.config(labelanchor = "n")

        self.INSTRUCTION = StringVar()
        self.INSTRUCTION.set("Instruction")
        
        self.machinecode = StringVar()
        self.machinecode.set("")

        self.codeEntry = Entry(self, textvariable=self.INSTRUCTION)

        #self.codeEntry.configure(font=("Helvetica", 12), width=40)
        self.codeEntry.configure(width=40)

        self.codeButton = Button(self, text="Compile")

        self.VHPL = Label(self, text="VHPL")

        self.codeButton.grid(row=0, column=0, rowspan=4, sticky="wens")

        self.VHPL.grid(row=0, column=1, sticky="wens")
        self.VHPL.config(relief=GROOVE, borderwidth=2)
        
        self.codeEntry.grid(row=1, column=1, sticky="wens")
        self.codeEntry.config(fg="green", bg="black")
        
        self.pack()
Example #3
0
class ReadOnlyEntry(Frame):
    def __init__(self, master, withFocus = True):
        '''
        withFocus -> enabled
            User can set the widget to focus, but the widget will not update
            while it has user focus (even programatically it cannot be updated)

        withFocus -> disabled
            User cannot set focus on the Entry widget. The moment it gets focus,
            focus is shifted to a dummy Frame.
            Widget can be updated programatically anytime.

        Note: in both cases the widget is readonly
        '''
        Frame.__init__(self, master)
        self.master = master
        self.withFocus = withFocus

        self.hasFocus = False
        vcmd = (self.master.register(self.onValidate),
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.readOnlyEntry = Entry(self, justify=CENTER, validate="all", validatecommand=vcmd, width=50)
        self.readOnlyEntry.grid(row=0, column=0)
        self.dummyFrame = Frame(self)
        self.dummyFrame.grid(row=0, column=1)

    def onValidate(self, d, i, P, s, S, v, V, W):
        """
        If withFocus is True, then do not accept keyboard inputs
        If withFocus is False, set focus to the dummy Frame that is not visible
        """
        if self.withFocus == True:
            if V == "focusin":
                self.hasFocus = True
            elif V == "focusout":
                self.hasFocus = False

            if self.hasFocus == False and V == "key":
                    return True
            else:
                return False
        else:
            if V == "focusin":
                self.dummyFrame.focus_set()
            return True


    def configure(self, **kwargs):
        self.readOnlyEntry.configure(**kwargs)

    def config(self, **kwargs):
        self.configure(**kwargs)

    def get(self):
        return self.readOnlyEntry.get()

    def set(self, text):
        self.readOnlyEntry.delete(0, END)
        self.readOnlyEntry.insert(0, text)
    def __init__(self):
        window=Tk()
        window.title('Scientific Calculator')
        window.configure(background="white")
        self.string=StringVar()
        entry=Entry(window,textvariable=self.string)
        entry.grid(row=0,column=0,columnspan=6)
        entry.configure(background="white")
        entry.focus()
        
        values=["7","8","9","/","%","clear","AC",
                "4","5","6","*","(",")","**",
                "1","2","3","-","=",",","0",".","min","+","sin","asin","cos","acos","tan()",
                "pow","log10","max","abs","floor","pi","e","log","ceil","degrees","radians"]
        text=1
        i=0
        row=1
        col=0
        for txt in values:
            padx=10
            pady=10
            if(i==7):
                row=2
                col=0
            if(i==14):
                row=3
                col=0
            if(i==19):
                row=4
                col=0
            if(i==26):
                row=5
                col=0
            if(i==33):
                row=6
                col=0
            if(txt=='='):
                btn=Button(window,height=2,width=4,padx=70,pady=pady,text=txt,command=lambda txt=txt:self.equals())
                btn.grid(row=row,column=col,columnspan=3,padx=2,pady=2)
                btn.configure(background="yellow")

            elif(txt=='clear'):
                btn=Button(window,height=2,width=4,padx=padx,pady=pady, text=txt ,command=lambda txt=txt:self.delete())
                btn.grid(row=row,column=col,padx=1,pady=1)
                btn.configure(background="grey")
            elif(txt=='AC'):
                btn=Button(window,height=2,width=4,padx=padx,pady=pady,text=txt,command=lambda txt=txt:self.clearall())
                btn.grid(row=row,column=col,padx=1,pady=1)
                btn.configure(background="red")
            else:
                btn=Button(window,height=2,width=4,padx=padx,pady=pady,text=txt ,command=lambda txt=txt:self.addChar(txt))
                btn.grid(row=row,column=col,padx=1,pady=1)
                btn.configure(background="cyan")

            col=col+1
            i=i+1
        window.mainloop()
Example #5
0
 def __init__(self):
     window=Tk()
     window.title('Calculator')
     window.configure(background="black")
     self.string=StringVar()
     entry=Entry(window,textvariable=self.string)
     entry.grid(row=0,column=0,columnspan=20)
     entry.configure(background="white")
     entry.focus()        
     values=["7","8","9","/","%","clear",
             "4","5","6","*","+","AC",
             "1","2","3","-","0","="]
     text=1
     i=0
     row=1
     col=0
     for txt in values:
         padx=5
         pady=5
         if(i==6):
             row=2
             col=0
         if(i==12):
             row=3
             col=0
         if(i==18):
             row=4
             col=0
         
         if(txt=='='):
             btn=Button(window,height=2,width=4,padx=50,pady=pady,text=txt,command=lambda txt=txt:self.equals())
             btn.grid(row=row,column=col,columnspan=3,padx=1,pady=1)
             btn.configure(background="red")
         elif(txt=='clear'):
             btn=Button(window,height=2,width=4,padx=padx,pady=pady, text=txt ,command=lambda txt=txt:self.delete())
             btn.grid(row=row,column=col,padx=1,pady=1)
             btn.configure(background="yellow")
         elif(txt=='AC'):
             btn=Button(window,height=2,width=4,padx=padx,pady=pady,text=txt,command=lambda txt=txt:self.clearall())
             btn.grid(row=row,column=col,padx=1,pady=1)
             btn.configure(background="red")
         else:
             btn=Button(window,height=2,width=4,padx=padx,pady=pady,text=txt ,command=lambda txt=txt:self.addChar(txt))
             btn.grid(row=row,column=col,padx=1,pady=1)
             btn.configure(background="grey")
         col=col+1
         i=i+1
     window.mainloop()      
Example #6
0
class GenerateMaterialDialog(tkSimpleDialog.Dialog):

    choises = ['4+2j', 'air', 'glass', 'water', 'alloyAuAg']

    def __init__(self, master, data_name='1.0', data_conc=0):
        self.data_name = data_name
        self.data_conc = data_conc
        tkSimpleDialog.Dialog.__init__(self, master)

    def body(self, master):
        Label(master, text='Material name:').grid(row=1)
        Label(master, text='Concentration:').grid(row=2)

        self.ename = ttk.Combobox(master, values=self.choises)
        self.ename.bind('<<ComboboxSelected>>', self._cbselected)
        self.ename.current(0)
        self.econc = Entry(master, state='disabled')
        self.econc.insert(0, self.data_conc)

        self.ename.grid(row=1, column=1)
        self.econc.grid(row=2, column=1)
        return self.ename  # initial focus

    def _cbselected(self, event=None):
        if self.ename.get() == 'alloyAuAg':
            self.econc.configure(state='normal')
        else:
            self.econc.configure(state='disabled')

    def validate(self):
        try:
            name = self.ename.get()
            if not (name in self.choises):
                _ = np.complex(self.ename.get())
            if name == 'alloyAuAg':
                self.result = name, float(self.econc.get())
            else:
                self.result = name, None
            return True
        except ValueError as err:
            tkMessageBox.showerror('Error', 'Bad data entered\n%s' % err)
            return False

    def apply(self):
        pass
class Application:

    def __init__(self, master):
        self.master = master
        self.master.title("City Information")
        self.master.geometry('350x200')

        self.data = pd.read_json('ca.json')
        self.tkvar = StringVar(master)
        self.choices = set(self.data.name)
        self.tkvar.set(self.data.name.values[0])
        self.dropdown = OptionMenu(master, self.tkvar, *self.choices, command=self.onSelectChange)
        self.dropdown.grid(column=1, row=0)

        self.cityLabel = Label(master, text="City")
        self.cityLabel.grid(column=0, row=0)

        self.countyLabel = Label(master, text="County")
        self.countyLabel.grid(column=0, row=1)

        self.countyEntry = Entry(master, width=25)
        self.countyEntry.configure(state='readonly')
        self.countyEntry.grid(column=1, row=1)

        self.latLabel = Label(master, text='Latitude')
        self.latLabel.grid(column=0, row=2)

        self.latEntry = Entry(master, width=25)
        self.latEntry.configure(state='readonly')
        self.latEntry.grid(column=1, row=2)

        self.longLabel = Label(master, text='Longitude')
        self.longLabel.grid(column=0, row=3)

        self.longEntry = Entry(master, width=25)
        self.longEntry.configure(state='readonly')
        self.longEntry.grid(column=1, row=3)

        self.onSelectChange()
    
    def onSelectChange():
        self.
Example #8
0
class FilePickEdit(Frame):
    
    def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, 
                 rename_on_edit=0, font = None, coloring=True, allowNone=False, highlighter=None, directory='.'):
        '''
            file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"])
        '''
        self.master = master
        self.directory = directory
        self.user_onChange = user_onChange
        Frame.__init__(self, master)
        row = 0
        self.unmodified = True
        self.allowNone = allowNone
        self.file_extension = ""
        if type(file_mask) != list:
            file_mask = [file_mask]
        if "." in file_mask[0]:
            self.file_extension = file_mask[0][file_mask[0].rfind('.'):]
        # read filenames
        self.file_mask = file_mask
        self.updateList()
        # filename frame
        self.list_frame = Frame(self)
        self.list_frame.grid(row=row, column=0, sticky="WE")
        self.list_frame.columnconfigure(0, weight=1)
        # create list
        self.picked_name = StringVar(self)
        self.makelist()
        # refresh button
        self.refresh_button = Button(self.list_frame, text='<- refresh', command=self.refresh, height=1)
        self.refresh_button.grid(row=0, column=1, sticky='E')        
        # save button
        self.save_button = Button(self.list_frame, text="save", command=self.save, height=1)
        self.save_button.grid(row=0, column=2, sticky="E")
        # editor
        row += 1
        if coloring:
            self.editor = SyntaxHighlightingText(self, self.onEdit, highlighter=highlighter)
        else:
            self.editor = ScrolledText2(self, self.onEdit)
        if font != None:
            self.editor.configure(font=font)
        if edit_height is not None:
            self.editor.configure(height=edit_height)
        self.editor.grid(row=row, column=0, sticky="NEWS")
        self.rowconfigure(row, weight=1)
        self.columnconfigure(0, weight=1)
        # option to change filename on edit
        row += 1
        self.options_frame = Frame(self)
        self.options_frame.grid(row=row, column=0, sticky=W)
        self.rename_on_edit = IntVar()
        self.cb = Checkbutton(self.options_frame, text="rename on edit", variable=self.rename_on_edit)
        self.cb.pack(side=LEFT)
        self.cb.configure(command=self.onChangeRename)
        self.rename_on_edit.set(rename_on_edit)
        # filename frame
        row += 1
        self.filename_frame = Frame(self)
        self.filename_frame.grid(row=row, column=0, sticky="WE")
        self.filename_frame.columnconfigure(0, weight=1)
        # save as filename
        self.save_name = StringVar(self)
        self.save_edit = Entry(self.filename_frame, textvariable = self.save_name)
        self.save_edit.grid(row=0, column=0, sticky="WE")
        self.save_name.trace("w", self.onSaveChange)
        # pick default if applicableButton
        self.select(default_file)
        self.row = row
        
    def setDirectory(self, directory, keep=False):
        self.directory = directory
        self.updateList()
        self.makelist()
#         menu = self.list["menu"] scrolledlist
#         menu = self.list.listbox#["scrolledlist"]
#         menu.delete(0, 'end')
        # add the new ones
#         for filename in self.files:
#             menu.add_command(label=filename, command=_setit(self.picked_name, filename, None))
        # if keep is true, only the files list will be updated but the content of the
        # text area will not be altered/removed
        if not keep: self.select("")
    
    def refresh(self):
        sel = self.get()
        self.updateList()
        self.select(sel, notify=False)
    
    def reloadFile(self):
        self.editor.delete("1.0", END)
        filename = self.picked_name.get()
        if os.path.exists(os.path.join(self.directory, filename)):
            new_text = file(os.path.join(self.directory, filename)).read()
            if new_text.strip() == "":
                new_text = "// %s is empty\n" % filename;
            new_text = new_text.replace("\r", "")
        else:
            new_text = ""
        self.editor.insert(INSERT, new_text)
        
    def setText(self, txt):
        '''
        Replaces the text in the edit field as by typing
        into it.
        '''
        self.select("")
        if txt.strip() == "":
            txt = "// empty database\n";
        self.editor.insert(INSERT, txt)
        self.onEdit()
        

    def onSelChange(self, name, index=0, mode=0):
        self.reloadFile()
        filename = self.picked_name.get()
        self.save_name.set(filename)
        self.save_edit.configure(state=DISABLED)
        self.unmodified = True
        if self.user_onChange != None:
            self.user_onChange(filename)

    def onSaveChange(self, name, index, mode): pass
#         if self.user_onChange != None:
#             self.user_onChange(self.save_name.get())

    def autoRename(self):
        # modify "save as" name
        filename = self.picked_name.get()
        if filename == "": filename = "new" + self.file_extension # if no file selected, create new filename
        ext = ""
        extpos = filename.rfind(".")
        if extpos != -1: ext = filename[extpos:]
        base = filename[:extpos]
        hpos = base.rfind("-")
        num = 0
        if hpos != -1:
            try:
                num = int(base[hpos+1:])
                base = base[:hpos]
            except:
                pass
        while True:
            num += 1
            filename = "%s-%d%s" % (base, num, ext)
            if not os.path.exists(filename):
                break
        self.save_name.set(filename)
        # user callback
        if self.user_onChange != None:
            self.user_onChange(filename)

    def onEdit(self):
        if self.unmodified == True:
            self.unmodified = False
            # do auto rename if it's enabled or there is no file selected (editing new file)
            if self.rename_on_edit.get() == 1 or self.picked_name.get() == "":
                self.autoRename()
            # enable editing of save as name
            self.save_edit.configure(state=NORMAL)

    def onChangeRename(self):
        # called when clicking on "rename on edit" checkbox
        if self.rename_on_edit.get() == 1:
            if (not self.unmodified) and self.save_name.get() == self.picked_name.get():
                self.autoRename()
        else:
            self.save_name.set(self.picked_name.get())

    def updateList(self):
        self.files = []
        if self.allowNone:
            self.files.append("")
        if os.path.exists(self.directory):
            for filename in os.listdir(self.directory):
                for fm in self.file_mask:
                    if fnmatch(filename, fm):
                        self.files.append(filename)
        self.files.sort()
        if len(self.files) == 0 and not self.allowNone: self.files.append("(no %s files found)" % str(self.file_mask    ))
        

    def select(self, filename, notify=True):
        ''' selects the item given by filename '''
        if filename in self.files:
            if not havePMW:
                self.picked_name.set(filename)
            else:
                self.list.selectitem(self.files.index(filename))
                if notify: self.onSelChange(filename)
        else:
            self.editor.delete("1.0", END)
                

    def makelist(self):
        if havePMW:
            self.list = Pmw.ComboBox(self.list_frame,
                    selectioncommand = self.onSelChange,
                    scrolledlist_items = self.files,
            )
            self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS")
            self.list.component('entryfield').component('entry').configure(state = 'readonly', relief = 'raised')
            self.picked_name = self.list
        else:
            self.list = apply(OptionMenu, (self.list_frame, self.picked_name) + tuple(self.files))
            self.list.grid(row=0, column=0, sticky="NEW")
            self.picked_name.trace("w", self.onSelChange)

    def save(self):
        self.get()

    def set(self, selected_item):
        self.select(selected_item)

    def get(self):
        ''' gets the name of the currently selected file, saving it first if necessary '''
        filename = self.save_name.get()
        if self.unmodified == False:
            self.unmodified = True
            # save the file
            f = file(os.path.join(self.directory, filename), "w")
            f.write(self.editor.get("1.0", END).encode('utf-8'))
            f.close()
            # add it to the list of files
#             if not filename in self.files:
#                 self.files.append(filename)
#                 self.files.sort()
#                 self.list.destroy()
#                 self.makelist()
            # set it as the new pick
            #if havePMW:
            #    self.picked_name.selectitem(self.files.index(filename), 1)
            #else:
            #    self.picked_name.set(filename)
#             self.select(filename)
            self.refresh()
            self.select(filename, notify=False)
            self.save_edit.configure(state=DISABLED)
        return filename

    def get_text(self):
        return self.editor.get("1.0", END)

    def get_filename(self):
        return self.save_name.get()

    def set_enabled(self, state):
        self.editor.configure(state=state)
        if havePMW:
            self.list.component('entryfield_entry').configure(state=state)
#             self.list.component('arrowbutton').configure(state=state)
            self.list.component('arrowbutton').bind('<1>', (lambda a: 'break') if state==DISABLED else self.list._postList)
        else:
            self.list.configure(state=state)
        self.save_button.configure(state=state)
        self.cb.configure(state=state)
        self.save_edit.configure(state=state)
Example #9
0
class Chatbox(object):
    def __init__(self,
                 master,
                 my_nick=None,
                 command=None,
                 topic=None,
                 entry_controls=None,
                 maximum_lines=None,
                 timestamp_template=None,
                 scrollbar_background=None,
                 scrollbar_troughcolor=None,
                 history_background=None,
                 history_font=None,
                 history_padx=None,
                 history_pady=None,
                 history_width=None,
                 entry_font=None,
                 entry_background=None,
                 entry_foreground=None,
                 label_template=u"{nick}",
                 label_font=None,
                 logging_file='log.txt',
                 tags=None):
        self._master = master
        self.interior = Frame(master, class_="Chatbox")

        self._command = command

        self._is_empty = True

        self._maximum_lines = maximum_lines
        self._timestamp_template = timestamp_template

        self._command = command

        self._label_template = label_template

        self._logging_file = logging_file

        if logging_file is None:
            self._log = None
        else:
            try:
                self._log = open(logging_file, "a")
            except:
                self._log = None

        ####    INSTRUCTION:

        self.title_font = tkfont.Font(family='Helvetica',
                                      size=18,
                                      weight="bold")
        self.content_font = tkfont.Font(family='Helvetica', size=13)
        self.instruction_font = tkfont.Font(family='Courier', size=13)

        instruction_label_frame = Frame(self.interior,
                                        class_="Instruction_label")
        instruction_label_frame.pack(fill=X)

        self._label_instruction = Label(instruction_label_frame,
                                        text="INSTRUCTIONS",
                                        font=self.title_font)
        self._label_instruction.pack(side=LEFT)

        instruction_frame = Frame(self.interior, class_="Instruction")
        instruction_frame.pack(fill=X)

        self._text_instruction = Text(instruction_frame,
                                      height=13,
                                      borderwidth=2,
                                      relief="groove",
                                      font=self.instruction_font)
        self._text_instruction.pack(fill=X, side=LEFT, expand=True)
        quote = """1. Read the question.
2. Fill your answer  
   Please answer in a COMPLETE SENTENCE, not just keywords.    
   
   Example:
   Good:                                          Bad:
   Question: What kind of food do you like?       Question: What kind of food do you like?
   Reply: I like spicy food.                      Reply: spicy food.
   
   If you are reluctant to answer the question, click "Next Dialogue" button to go to the next question.
3. press Enter to submit your answer. 
4. Rate the reply question in the Evaluation section
5. Click "Next Dialogue" button at the bottom to continue. """
        self._text_instruction.insert(END, quote)

        counter_frame = Frame(self.interior)
        counter_frame.pack(fill=X)

        global counter_question
        counter_question = StringVar()
        counter_question.set(str(1))

        Label(counter_frame, text="").pack(side='top', anchor='w')
        self._label_counter_1 = Label(counter_frame,
                                      text="DIALOGUE",
                                      font=self.title_font).pack(side=LEFT)
        self._label_counter_2 = Label(counter_frame,
                                      textvariable=counter_question,
                                      font=self.title_font).pack(side=LEFT)
        self._label_counter_3 = Label(counter_frame,
                                      text="OF 10 ",
                                      font=self.title_font).pack(side=LEFT)

        ####     MESSAGE DISPLAY AREA:

        top_frame = Frame(self.interior, class_="Top")
        top_frame.pack(
            expand=True, fill=BOTH
        )  # True: the widget is expanded to fill any extra space, BOTH: fill X&Y

        self._textarea = Text(top_frame,
                              height=1,
                              borderwidth=2,
                              relief="groove",
                              state=DISABLED,
                              font=self.content_font)

        self._vsb = Scrollbar(top_frame,
                              takefocus=0,
                              command=self._textarea.yview)
        self._vsb.pack(side=RIGHT,
                       fill=Y)  #scroll bar di kanan, sepanjang sumbu Y

        self._textarea.pack(side=RIGHT, expand=YES, fill=BOTH)
        self._textarea.insert(END, '\n')
        self._textarea[
            "yscrollcommand"] = self._vsb.set  # text area tempat display chat

        ####     MESSAGE ENTRY:

        entry_frame = Frame(self.interior, class_="Chatbox_Entry")
        entry_frame.pack(
            fill=X, anchor=N
        )  # fill=X: make all widgets as wide as parent widget, anchor=N: place the text at the top

        #self.var_entry = StringVar()

        if entry_controls is not None:
            controls_frame = Frame(entry_frame, class_="Controls")
            controls_frame.pack(fill=X)
            entry_controls(controls_frame, chatbox=self)

            bottom_of_entry_frame = Frame(entry_frame)
            self._entry_label = Label(bottom_of_entry_frame)
            self._entry = Entry(
                bottom_of_entry_frame)  #,textvariable=self.var_entry
        else:
            self._entry_label = Label(entry_frame)
            self._entry = Entry(
                entry_frame)  #, width = 70, textvariable=self.var_entry

        self._entry.pack(side=LEFT, fill=X, expand=YES)
        self._entry.bind(
            "<Return>", self._on_message_sent
        )  # when user press enter in the chatbox, call on_message_sent
        self._entry.focus()

        #self._buttonmessage = Button(entry_frame, text="Submit", width = 20, command=self._on_message_sent)
        #self._buttonmessage.bind("<Button-1>", self._on_message_sent) # bind the action of the left button of your mouse to the button assuming your primary click button is the left one.
        #self._buttonmessage.pack(side=LEFT)

        ####

        label_evaluation = Frame(self.interior)
        label_evaluation.pack(fill=X, anchor=N)

        Label(label_evaluation, text="").pack(side='top', anchor='w')
        Label(label_evaluation, text="EVALUATION",
              font=self.title_font).pack(side='top', anchor='w')
        Label(
            label_evaluation,
            text=
            "Please indicate how strongly you agree or disagree with all the following statements."
        ).pack(side='top', anchor='w')
        #Label(label_evaluation, text="").pack(side='top', anchor='w')

        ####    QUESTIONNAIRES:
        ''' Questionnaire frame'''

        question_frame = Frame(self.interior)
        #question_frame.grid(column=0, row=0, sticky=(N, W, E, S))
        #question_frame.columnconfigure(0, weight=1)
        #question_frame.rowconfigure(0, weight=1)
        #self.configure(background="white")
        question_frame.pack()

        self.var_q1 = IntVar()
        self.var_q2 = IntVar()
        self.var_q3 = IntVar()
        self.var_q4 = IntVar()
        self.var_q1.set(0)  # none selected
        self.var_q2.set(0)  # none selected
        self.var_q3.set(0)  # none selected
        self.var_q4.set(0)  # none selected

        #Label(question_frame, text="").grid(column=0, row=0, sticky="W")
        #Label(question_frame, text="EVALUATION", font=self.title_font).grid(column=0, row=1, sticky="W")

        Label(question_frame, text="Strongly disagree").grid(column=1,
                                                             row=3,
                                                             padx=4)
        Label(question_frame, text="Disagree").grid(column=2, row=3, padx=4)
        Label(question_frame, text="Neither agree nor disagree").grid(column=3,
                                                                      row=3,
                                                                      padx=4)
        Label(question_frame, text="Agree").grid(column=4, row=3, padx=4)
        Label(question_frame, text="Strongly agree").grid(column=5,
                                                          row=3,
                                                          padx=4)

        Label(question_frame,
              text="The grammar of the reply question is correct").grid(
                  column=0, row=4, sticky="W")
        Radiobutton(question_frame, variable=self.var_q1,
                    value=1).grid(column=1, row=4)
        Radiobutton(question_frame, variable=self.var_q1,
                    value=2).grid(column=2, row=4)
        Radiobutton(question_frame, variable=self.var_q1,
                    value=3).grid(column=3, row=4)
        Radiobutton(question_frame, variable=self.var_q1,
                    value=4).grid(column=4, row=4)
        Radiobutton(question_frame, variable=self.var_q1,
                    value=5).grid(column=5, row=4)

        Label(
            question_frame,
            text=
            "The reply question is appropriate to be asked \nin a conversation",
            justify=LEFT).grid(column=0, row=5, sticky="W")
        Radiobutton(question_frame, variable=self.var_q2,
                    value=1).grid(column=1, row=5)
        Radiobutton(question_frame, variable=self.var_q2,
                    value=2).grid(column=2, row=5)
        Radiobutton(question_frame, variable=self.var_q2,
                    value=3).grid(column=3, row=5)
        Radiobutton(question_frame, variable=self.var_q2,
                    value=4).grid(column=4, row=5)
        Radiobutton(question_frame, variable=self.var_q2,
                    value=5).grid(column=5, row=5)

        Label(question_frame,
              text="The reply question is related to my answer").grid(
                  column=0, row=6, sticky="W")
        Radiobutton(question_frame, variable=self.var_q3,
                    value=1).grid(column=1, row=6)
        Radiobutton(question_frame, variable=self.var_q3,
                    value=2).grid(column=2, row=6)
        Radiobutton(question_frame, variable=self.var_q3,
                    value=3).grid(column=3, row=6)
        Radiobutton(question_frame, variable=self.var_q3,
                    value=4).grid(column=4, row=6)
        Radiobutton(question_frame, variable=self.var_q3,
                    value=5).grid(column=5, row=6)

        Label(question_frame,
              text="The dialogue as a whole feels natural").grid(column=0,
                                                                 row=7,
                                                                 sticky="W")
        Radiobutton(question_frame, variable=self.var_q4,
                    value=1).grid(column=1, row=7)
        Radiobutton(question_frame, variable=self.var_q4,
                    value=2).grid(column=2, row=7)
        Radiobutton(question_frame, variable=self.var_q4,
                    value=3).grid(column=3, row=7)
        Radiobutton(question_frame, variable=self.var_q4,
                    value=4).grid(column=4, row=7)
        Radiobutton(question_frame, variable=self.var_q4,
                    value=5).grid(column=5, row=7)

        #E1 = Entry(question_frame)

        ####    NEXT QUESTIONS BUTTON:
        button_next = Frame(self.interior, class_="Evaluation_3")
        button_next.pack(fill=X, anchor=N)

        Label(button_next, text="").pack(side='top', anchor='w')
        Label(
            button_next,
            text=
            "Please give your comment here.\nFor example, give the reason why do you think the reply question is not appropriate, \nincorrect grammar, not related to your answer, or why it does not feel natural.",
            justify=LEFT).pack(side='top', anchor='w')

        self.var_comment = StringVar()
        self.E1 = Entry(button_next, textvariable=self.var_comment)
        self.E1.pack(side='top', anchor='w', expand=YES, fill=X)
        Label(button_next, text="").pack()

        #button
        self._button_next = Button(button_next,
                                   text="Next Dialogue >>",
                                   command=self._on_click_next,
                                   width=50)
        self._button_next.pack()

        ####

        if history_background:
            self._textarea.configure(background=history_background)

        if history_font:
            self._textarea.configure(font=history_font)

        if history_padx:
            self._textarea.configure(padx=history_padx)

        if history_width:
            self._textarea.configure(width=history_width)

        if history_pady:
            self._textarea.configure(pady=history_pady)

        if scrollbar_background:
            self._vsb.configure(background=scrollbar_background)

        if scrollbar_troughcolor:
            self._vsb.configure(troughcolor=scrollbar_troughcolor)

        if entry_font:
            self._entry.configure(font=entry_font)

        if entry_background:
            self._entry.configure(background=entry_background)

        if entry_foreground:
            self._entry.configure(foreground=entry_foreground)

        if label_font:
            self._entry_label.configure(font=label_font)

        if tags:
            for tag, tag_config in tags.items():
                self._textarea.tag_config(tag, **tag_config)

        self.set_nick(my_nick)

    @property
    def topic(self):
        return

    @topic.setter
    def topic(self, topic):
        return

    def focus_entry(self):
        self._entry.focus()

    def bind_entry(self, event, handler):
        self._entry.bind(event, handler)

    def bind_textarea(self, event, handler):
        self._textarea.bind(event, handler)

    def bind_tag(self, tagName, sequence, func, add=None):
        self._textarea.tag_bind(tagName, sequence, func, add=add)

    def focus(self):
        self._entry.focus()

    def user_message(self, nick, content):
        if self._timestamp_template is None:
            self._write((u"%s:" % nick, "nick"), " ",
                        (content, "user_message"))
        else:
            timestamp = datetime.datetime.now().strftime(
                self._timestamp_template)
            self._write((timestamp, "timestamp"), " ", (u"%s:" % nick, "nick"),
                        " ", (content, "user_message"))

    def notification_message(self, content, tag=None):
        if tag is None:
            tag = "notification"

        self._write((content, tag))

    notification = notification_message

    def notification_of_private_message(self, content, from_, to):
        if self._timestamp_template is None:
            self.notification_message(
                u"{from_} -> {to}: {content}".format(from_=from_,
                                                     to=to,
                                                     content=content),
                "notification_of_private_message")
        else:
            timestamp = datetime.datetime.now().strftime(
                self._timestamp_template)
            self.notification_message(
                u"{timestamp} {from_} -> {to}: {content}".format(
                    timestamp=timestamp, from_=from_, to=to, content=content),
                "notification_of_private_message")

    def new_message(self, message):
        if isinstance(message, User_Message):
            self.user_message(message.content, message.nick)
        elif isinstance(message, Notification_Message):
            self.notification(message.content, message.tag)
        elif isinstance(message, Notification_Of_Private_Message):
            self.notification_of_private_message(message.from_, message.to,
                                                 message.content)
        else:
            raise Exception("Bad message")

    def tag(self, tag_name, **kwargs):
        self._textarea.tag_config(tag_name, **kwargs)

    def clear(self):
        self._is_empty = True
        self._textarea.delete('1.0', END)

    @property
    def logging_file(self):
        return self._logging_file

    def send(self, content):
        if self._my_nick is None:
            raise Exception("Nick not set")

        self.user_message(self._my_nick, content)

    def _filter_text(self, text):
        return "".join(ch for ch in text if ch <= u"\uFFFF")

    def _write(self, *args):
        if len(args) == 0: return

        relative_position_of_scrollbar = self._vsb.get()[1]

        self._textarea.config(state=NORMAL)

        if self._is_empty:
            self._is_empty = False
        else:
            self._textarea.insert(END, "\n")
            if self._log is not None:
                self._log.write("\n")

        for arg in args:
            if isinstance(arg, tuple):
                text, tag = arg
                # Parsing not allowed characters
                text = self._filter_text(text)
                self._textarea.insert(END, text, tag)
            else:
                text = arg

                text = self._filter_text(text)
                self._textarea.insert(END, text)

            if self._log is not None:
                self._log.write(text)

        if self._maximum_lines is not None:
            start_line = int(self._textarea.index('end-1c').split('.')
                             [0]) - self._maximum_lines

            if lines_to_delete >= 1:
                self._textarea.delete('%s.0' % start_line, END)

        self._textarea.config(state=DISABLED)

        if relative_position_of_scrollbar == 1:
            self._textarea.yview_moveto(1)

    def _on_message_sent(self, event):

        if not self._entry.get():  # or not self.var_entry.get()
            showwarning('Empty answer', 'Please fill your anwer')
        else:
            #  update flag press enter
            global flag_press_enter
            global counter_enter_global

            if flag_press_enter == False:
                flag_press_enter = True
                #counter_enter += 1

            if flag_press_enter == True:
                if counter_enter_global < 2:

                    counter_enter_global += 1

                    # get the input from user
                    #print("var_entry:",self.var_entry.get())
                    message = self._entry.get()
                    # clear entry
                    self._entry.delete(0, END)

                    self.send(message)

                    if self._command:
                        self._command(
                            message)  # display user input to the chat window

                    if counter_enter_global > 1:
                        self._textarea.config(state=NORMAL)
                        self._textarea.insert(
                            END,
                            "\n[Thank you for your response. Continue to evaluate the Reply Question]"
                        )
                        self._textarea.config(state=DISABLED)

                    else:
                        ''' running the follow-up question generation '''

                        with open(input_path, 'w') as f:
                            f.write("%s\n" % message)

                        pp.preprocess_senna_input(input_path, senna_input_path)
                        rs.runSENNA(senna_input_file)

                        # getting semantic representation
                        sentenceList, dlines = fqg.create_SR(senna_input_path)

                        # generate the questions
                        listOfAllGeneratedQA = fqg.generate_questions(
                            sentenceList, dlines)
                        print(listOfAllGeneratedQA)

                        #reply_list = random.choice(listOfAllGeneratedQA[0])
                        reply = rs.ranking(listOfAllGeneratedQA)

                        if self._log is not None:
                            self._log.write("\nTemplate: %s" %
                                            listOfAllGeneratedQA)
                        #reply = reply_list[0]
                        print(reply)
                        self.user_message("Reply question", reply)

                else:
                    showinfo(
                        'Thank you',
                        'Thank you for your response. Please continue to evaluate the Reply Question'
                    )
                    self._entry.focus()

    def set_nick(self, my_nick):
        self._my_nick = my_nick

        if my_nick:
            text = self._label_template.format(nick=my_nick)

            self._entry_label["text"] = text
            self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry)
        else:
            self._entry_label.pack_forget()

    def _on_click_next(self):
        global flag_press_enter
        global counter_enter_global
        maximum_counter = 10

        if flag_press_enter == True and self.var_q1.get(
        ) != 0 and self.var_q2.get() != 0 and self.var_q3.get(
        ) != 0 and self.var_q4.get() != 0:
            global counter_question_global

            if self._log is not None:
                self._log.write("\nDialogue number: %s" %
                                str(counter_question_global))

            # increase question counter
            counter_question_global += 1

            # write questionnaire's answers to log file
            if self._log is not None:
                self._log.write("\nQ1: %s" % self.var_q1.get())
                self._log.write("\nQ2: %s" % self.var_q2.get())
                self._log.write("\nQ3: %s" % self.var_q3.get())
                self._log.write("\nQ3: %s" % self.var_q4.get())
                self._log.write("\nComment: %s" % self.var_comment.get())

        #print ('debug: ',self.var_q1.get())
        if counter_question_global > maximum_counter:
            showinfo(
                'Finish',
                'Thank you for your participation! \nWe will now save your responses. \nPress OK to close the application.'
            )
            if OK:
                self._master.destroy()
                global flag_close
                flag_close = True
        elif self.var_q1.get() == 0 and flag_press_enter == True:
            showinfo('Rate the evaluation', 'Please rate all evaluations.')
        elif self.var_q2.get() == 0 and flag_press_enter == True:
            showinfo('Rate the evaluation', 'Please rate all evaluations.')
        elif self.var_q3.get() == 0 and flag_press_enter == True:
            showinfo('Rate the evaluation', 'Please rate all evaluations.')
        elif self.var_q4.get() == 0 and flag_press_enter == True:
            showinfo('Rate the evaluation', 'Please rate all evaluations.')
        else:
            # clear chat area
            self._textarea.config(state=NORMAL)
            self._textarea.delete('1.0', END)
            self._textarea.config(state=DISABLED)

            # fill with new starter's question
            with open(starter_questions) as f:
                dlines = f.read().splitlines(
                )  #reading a file without newlines
            starter = (random.choice(dlines))
            self.user_message("Question", starter)

            # update question counter
            counter_question.set(str(counter_question_global))

            # reset
            flag_press_enter = False
            counter_enter_global = 0
            self.var_q1.set(0)  # questionnaire 1
            self.var_q2.set(0)  # questionnaire 2
            self.var_q3.set(0)  # questionnaire 3
            self.var_q4.set(0)  # questionnaire 3
            self.E1.delete(0, END)  # clear comment
            self._entry.delete(0, END)  # clear entry message
Example #10
0
class Chatbox(object):
    def __init__(self,
                 master,
                 my_nick=None,
                 command=None,
                 topic=None,
                 entry_controls=None,
                 maximum_lines=None,
                 timestamp_template=None,
                 scrollbar_background=None,
                 scrollbar_troughcolor=None,
                 history_background=None,
                 history_font=None,
                 history_padx=None,
                 history_pady=None,
                 history_width=None,
                 entry_font=None,
                 entry_background=None,
                 entry_foreground=None,
                 label_template=u"{nick}",
                 label_font=None,
                 logging_file=None,
                 tags=None):
        self.interior = Frame(master, class_="Chatbox")

        self._command = command

        self._is_empty = True

        self._maximum_lines = maximum_lines
        self._timestamp_template = timestamp_template

        self._command = command

        self._label_template = label_template

        self._logging_file = logging_file

        if logging_file is None:
            self._log = None
        else:
            try:
                self._log = open(logging_file, "r")
            except:
                self._log = None

        top_frame = Frame(self.interior, class_="Top")
        top_frame.pack(expand=True, fill=BOTH)

        self._textarea = Text(top_frame, state=DISABLED)

        self._vsb = Scrollbar(top_frame,
                              takefocus=0,
                              command=self._textarea.yview)
        self._vsb.pack(side=RIGHT, fill=Y)

        self._textarea.pack(side=RIGHT, expand=YES, fill=BOTH)
        self._textarea["yscrollcommand"] = self._vsb.set

        entry_frame = Frame(self.interior, class_="Chatbox_Entry")
        entry_frame.pack(fill=X, anchor=N)

        if entry_controls is not None:
            controls_frame = Frame(entry_frame, class_="Controls")
            controls_frame.pack(fill=X)
            entry_controls(controls_frame, chatbox=self)

            bottom_of_entry_frame = Frame(entry_frame)
            self._entry_label = Label(bottom_of_entry_frame)
            self._entry = Entry(bottom_of_entry_frame)
        else:
            self._entry_label = Label(entry_frame)
            self._entry = Entry(entry_frame)

        self._entry.pack(side=LEFT, expand=YES, fill=X)
        self._entry.bind("<Return>", self._on_message_sent)

        self._entry.focus()

        if history_background:
            self._textarea.configure(background=history_background)

        if history_font:
            self._textarea.configure(font=history_font)

        if history_padx:
            self._textarea.configure(padx=history_padx)

        if history_width:
            self._textarea.configure(width=history_width)

        if history_pady:
            self._textarea.configure(pady=history_pady)

        if scrollbar_background:
            self._vsb.configure(background=scrollbar_background)

        if scrollbar_troughcolor:
            self._vsb.configure(troughcolor=scrollbar_troughcolor)

        if entry_font:
            self._entry.configure(font=entry_font)

        if entry_background:
            self._entry.configure(background=entry_background)

        if entry_foreground:
            self._entry.configure(foreground=entry_foreground)

        if label_font:
            self._entry_label.configure(font=label_font)

        if tags:
            for tag, tag_config in tags.items():
                self._textarea.tag_config(tag, **tag_config)

        self.set_nick(my_nick)

    @property
    def topic(self):
        return

    @topic.setter
    def topic(self, topic):
        return

    def focus_entry(self):
        self._entry.focus()

    def bind_entry(self, event, handler):
        self._entry.bind(event, handler)

    def bind_textarea(self, event, handler):
        self._textarea.bind(event, handler)

    def bind_tag(self, tagName, sequence, func, add=None):
        self._textarea.tag_bind(tagName, sequence, func, add=add)

    def focus(self):
        self._entry.focus()

    def user_message(self, nick, content):
        if self._timestamp_template is None:
            self._write((u"%s:" % nick, "nick"), " ",
                        (content, "user_message"))
        else:
            timestamp = datetime.datetime.now().strftime(
                self._timestamp_template)
            self._write((timestamp, "timestamp"), " ", (u"%s:" % nick, "nick"),
                        " ", (content, "user_message"))

    def notification_message(self, content, tag=None):
        if tag is None:
            tag = "notification"

        self._write((content, tag))

    notification = notification_message

    def notification_of_private_message(self, content, from_, to):
        if self._timestamp_template is None:
            self.notification_message(
                u"{from_} -> {to}: {content}".format(from_=from_,
                                                     to=to,
                                                     content=content),
                "notification_of_private_message")
        else:
            timestamp = datetime.datetime.now().strftime(
                self._timestamp_template)
            self.notification_message(
                u"{timestamp} {from_} -> {to}: {content}".format(
                    timestamp=timestamp, from_=from_, to=to, content=content),
                "notification_of_private_message")

    def new_message(self, message):
        if isinstance(message, User_Message):
            self.user_message(message.content, message.nick)
        elif isinstance(message, Notification_Message):
            self.notification(message.content, message.tag)
        elif isinstance(message, Notification_Of_Private_Message):
            self.notification_of_private_message(message.from_, message.to,
                                                 message.content)
        else:
            raise Exception("Bad message")

    def tag(self, tag_name, **kwargs):
        self._textarea.tag_config(tag_name, **kwargs)

    def clear(self):
        self._is_empty = True
        self._textarea.delete('1.0', END)

    @property
    def logging_file(self):
        return self._logging_file

    def send(self, content):
        if self._my_nick is None:
            raise Exception("Nick not set")

        self.user_message(self._my_nick, content)

    def _filter_text(self, text):
        return "".join(ch for ch in text if ch <= u"\uFFFF")

    def _write(self, *args):
        if len(args) == 0: return

        relative_position_of_scrollbar = self._vsb.get()[1]

        self._textarea.config(state=NORMAL)

        if self._is_empty:
            self._is_empty = False
        else:
            self._textarea.insert(END, "\n")
            if self._log is not None:
                self._log.write("\n")

        for arg in args:
            if isinstance(arg, tuple):
                text, tag = arg
                # Parsing not allowed characters
                text = self._filter_text(text)
                self._textarea.insert(END, text, tag)
            else:
                text = arg

                text = self._filter_text(text)
                self._textarea.insert(END, text)

            if self._log is not None:
                self._log.write(text)

        if self._maximum_lines is not None:
            start_line = int(self._textarea.index('end-1c').split('.')
                             [0]) - self._maximum_lines

            if lines_to_delete >= 1:
                self._textarea.delete('%s.0' % start_line, END)

        self._textarea.config(state=DISABLED)

        if relative_position_of_scrollbar == 1:
            self._textarea.yview_moveto(1)

    def _on_message_sent(self, event):
        message = self._entry.get()
        self._entry.delete(0, END)

        self.send(message)

        if self._command:
            self._command(message)

    def set_nick(self, my_nick):
        self._my_nick = my_nick

        if my_nick:
            text = self._label_template.format(nick=my_nick)

            self._entry_label["text"] = text
            self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry)
        else:
            self._entry_label.pack_forget()
Example #11
0
class Interface:

    def __init__(self, master):



        serverPort = 12000
        clientAddress = '255.255.255.255'
        serverSocket = socket(AF_INET, SOCK_DGRAM)
        serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        serverSocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        serverSocket.bind(('', serverPort))

        self.master = master
        master.title("              DDOS ATTACK - HTTP FLOOD")

        self.IP = None

        self.message = "TYPE IP TO BE ATTACKED :"
        self.label_text = StringVar()
        self.label_text.set(self.message)
        self.label = Label(master, textvariable=self.label_text,font=(None, 13),background ="black",fg ="white")

        vcmd = master.register(self.validate) # we have to wrap the command



        self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))
        self.entry.configure(insertwidth=2,highlightbackground= "black")


        validate_ip_args = partial(self.validate_IP, serverSocket, clientAddress, serverPort)
        self.attack_button = Button(master, text="Start Attack", command=validate_ip_args, height = 2, width = 20,  font=(None, 13), fg ="white", background ="black",highlightbackground= "black")

        stop_attack_args = partial(self.stop_attack, serverSocket, clientAddress, serverPort)
        self.stop_button = Button(master, text="Stop Attack", command=stop_attack_args, state=DISABLED, height = 2, width = 20, font=(None, 13), fg ="white", background = "black",highlightbackground= "black")


        self.label.grid(row=0, column=0, columnspan=2, sticky=W+E,  pady=20)
        self.entry.grid(row=1, column=0, columnspan=2, sticky=W+E, pady= 8)
        self.attack_button.grid(row=2, column=0, padx= 5,pady= 8)
        self.stop_button.grid(row=2, column=1, padx= 5, pady= 8)


    def validate(self, new_text):
        if not new_text: # the field is being cleablack
            self.IP = None
            return True
        else:
            IP = new_text
            self.IP=IP
            return True

    def validate_IP(self, serverSocket, clientAddress, serverPort):

        if (is_valid_ipv4(str(self.IP))):
            self.message = "VALID IP, CONTACTING SLAVES!"
            serverSocket.sendto("S/"+self.IP, (clientAddress, serverPort))
            self.attack_button.configure(state=DISABLED)
            self.stop_button.configure(state=NORMAL)
        else:
            self.message = "INVALID IP, TRY AGAIN"

        if self.IP is None:
            self.message = "TYPE IP TO BE ATTACKED :"

        self.label_text.set(self.message)

    def stop_attack(self, serverSocket, clientAddress, serverPort):
        self.entry.delete(0, END)

        self.IP = None
        serverSocket.sendto("B/", (clientAddress, serverPort))

        self.message = "TYPE IP TO BE ATTACKED :"
        self.label_text.set(self.message)

        self.attack_button.configure(state=NORMAL)
        self.stop_button.configure(state=DISABLED)
Example #12
0
def start():
    #CREATE THE WINDOW
    global prefstr
    window = Tkinter.Tk()
    screen_width = window.winfo_screenwidth()  # width of the screen
    screen_height = window.winfo_screenheight()  # height of the screen
    window.title("EvE Route Optimizer")
    window.geometry('%dx%d+%d+%d' % (680, 640, (screen_width / 2) - 340,
                                     (screen_height / 2) - 320))
    window.configure(background='gray')
    result = ScrolledText.ScrolledText(window, width=60, height=20)
    result.configure(font=("Arial Bold", 12), fg="white")
    result.configure(background='black')
    start_field = Entry(window, width=37, font=("Arial Bold", 12))
    end_field = Entry(window, width=37, font=("Arial Bold", 12))
    fixed_end_field = Entry(window, width=37, font=("Arial Bold", 12))
    iteration_field = Entry(window, width=6, font=("Arial Bold", 12))
    start_field.insert(0, "Origin")
    end_field.insert(0, "Destination")
    fixed_end_field.insert(0, "Fixed End Point")
    iteration_field.insert(0, "Cycles")
    result.pack()
    start_field.pack()
    end_field.pack()
    fixed_end_field.pack()
    iteration_field.pack()
    fixed_end_field.configure(state=DISABLED)

    try:
        version_url = "https://sites.google.com/site/ustleveonline/route_optimizer_version"
        version_response = urllib.urlopen(version_url).read()
        local_version_file = open("route_optimizer_version", "r")
        local_version = local_version_file.read()
        if str(local_version) != str(version_response):
            result.insert(
                INSERT, "\nAn update for EvE Route Optimizer is available.\n")
            result.see("end")
            webbrowser.open(
                "https://sites.google.com/site/ustleveonline/route-optimizer",
                new=1,
                autoraise=True)
        else:
            result.insert(INSERT, "\nEvE Route Optimizer is up to date.\n")
            result.see("end")
    except:
        result.insert(INSERT,
                      "\n" + "ERROR: Please check your internet connection!")
        result.see("end")

    #ADD A WAYPOINT
    def add_waypoint(Event=None):
        global o_system
        global d_system
        global waypoint_adding_done

        waypoint_adding_done = False
        o_system = start_field.get()
        d_system = end_field.get()
        if (o_system != "" and d_system != "" and o_system != "Origin"
                and d_system != "Destination"):
            try:
                number_of_routes = len(routes)
                start_field.delete(0, 'end')
                end_field.delete(0, 'end')
                start_field.insert(0, d_system)
                create_route(False)
                if len(routes) > number_of_routes:
                    result.insert(
                        INSERT,
                        "\n" + "Added Route: " + o_system + " to " + d_system)
                    result.see("end")
                else:
                    result.insert(
                        INSERT, "\n" +
                        "ERROR: Unable to get data from esi.evetech.net!")
                    result.see("end")
                waypoint_adding_done = True
            except:
                result.insert(INSERT, "\n" + "ERROR: Invalid!")
                result.see("end")

    #CREATE ROUTE USING GIVEN WAYPOINTS
    def create_route(optimizing):
        global routes
        global waypoints
        global o_system
        global d_system
        global prefstr

        #GET ORIGIN ID
        try:
            o_base = "https://esi.evetech.net/latest/search/?categories=solar_system&search="
            o_end = "&strict=true"
            o_url = o_base + o_system + o_end

            o_response = urllib.urlopen(o_url).read()
            o_split_response = o_response.split(":")
            o_id_section = o_split_response[1]
            o_id_leftbracket = o_id_section.replace('[', '')
            o_id_rightbracket = o_id_leftbracket.replace(']', '')
            o_id_final = o_id_rightbracket.replace('}', '')
        except:
            result.insert(
                INSERT,
                "\n" + "ERROR: Unable to get data from esi.evetech.net!")
            result.see("end")

        #GET DESTINATION ID
        try:
            d_base = "https://esi.evetech.net/latest/search/?categories=solar_system&search="
            d_end = "&strict=true"
            d_url = d_base + d_system + d_end

            d_response = urllib.urlopen(d_url).read()
            d_split_response = d_response.split(":")
            d_id_section = d_split_response[1]
            d_id_leftbracket = d_id_section.replace('[', '')
            d_id_rightbracket = d_id_leftbracket.replace(']', '')
            d_id_final = d_id_rightbracket.replace('}', '')
        except:
            result.insert(
                INSERT,
                "\n" + "ERROR: Unable to get data from esi.evetech.net!")
            result.see("end")

        #GET ROUTE
        try:
            r_base = "https://esi.evetech.net/latest/route/"
            r_end = "/?datasource=tranquility&flag="
            r_type = prefstr
            r_slash = "/"
            r_url = r_base + o_id_final + r_slash + d_id_final + r_end + r_type
        except:
            result.insert(
                INSERT,
                "\n" + "ERROR: Unable to get data from esi.evetech.net!")
            result.see("end")

        #IF THIS ROUTE IS PART OF THE ORIGINAL REQUEST, ADD IT TO THE LIST
        try:
            if optimizing == False:
                r_response = urllib.urlopen(r_url).read()
                routes.append(r_response)
                waypoints.append(o_system)
            else:
                r_response = urllib.urlopen(r_url).read()
                return r_response
        except:
            result.insert(
                INSERT,
                "\n" + "ERROR: Unable to get data from esi.evetech.net!")
            result.see("end")

    #OPTIMIZE THE ROUTE
    def optimize():
        global o_system
        global d_system
        global routes
        global waypoints
        global optimized_routes
        global previous_routes
        global tested_routes
        global total_routes
        global final_routes
        global origins
        global destinations
        global initialized
        global cycles
        global final_best_route
        global fixed_endpoint_name

        result.insert(INSERT, "\n")
        last_destination = ""
        last_route = [None] * 10000
        best_route = [None] * 10000
        sys1 = ""
        sys2 = ""
        waypoints.append(d_system)

        #GET AND DISPLAY THE TOTAL ROUTE DISTANCE IN NUMBER OF JUMPS
        total_distance = 0
        for route in routes:
            split_route = route.split(",")
            total_distance += len(split_route)
        result.insert(INSERT, "\n" + "Number of jumps: " + str(total_distance))
        result.see("end")

        if fixed_endpoint == False:
            #GET ID FOR THE ORIGIN
            split_for_origin = routes[0].split(",")
            first_origin = split_for_origin[0].split("[")[1]

            #GET ID FOR THE LAST STOP
            final_route = routes[len(routes) - 1]
            split_final_route = final_route.split(",")
            last_stop = split_final_route[len(split_final_route) -
                                          1].split("]")[0]

            try:
                #CONVERT ID TO NAME FOR ORIGIN
                first_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                first_end_url = "/?datasource=tranquility&language=en-us"
                first_final_url = first_begin_url + first_origin + first_end_url
                first_response = urllib.urlopen(first_final_url).read()
                first_final_origin = first_response.split(":")[2].split(
                    ",")[0].replace('"', "")
                d_system = first_final_origin

                #CONVERT ID TO NAME FOR DESTINATION
                endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                endpoint_end_url = "/?datasource=tranquility&language=en-us"
                endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url
                endpoint_response = urllib.urlopen(endpoint_final_url).read()
                endpoint_final_response = endpoint_response.split(
                    ":")[2].split(",")[0].replace('"', "")
                o_system = endpoint_final_response
            except:
                result.insert(
                    INSERT,
                    "\n" + "ERROR: Unable to get data from esi.evetech.net!")
                result.see("end")

            #GET AND DISPLAY THE TOTAL ROUTE DISTANCE INCLUDING RETURN TO ORIGIN
            return_route = create_route(True)
            return_distance = len(return_route.split(","))
            result.insert(
                INSERT, "\n" + "Including return to origin: " +
                str(total_distance + return_distance) + "\n")
            result.see("end")
        else:
            #SET DESTINATION TO THE FIXED ENDPOINT
            if fixed_endpoint_name != "" and fixed_endpoint_name != "Fixed End Point":
                try:
                    d_system = fixed_endpoint_name
                except:
                    result.insert(INSERT,
                                  "\n" + "ERROR: Invalid Fixed End Point!")
                    result.see("end")

            #GET THE ID FOR THE LAST STOP
            final_route = routes[len(final_routes) - 1]
            split_final_route = final_route.split(",")
            last_stop = split_final_route[len(split_final_route) -
                                          1].split("]")[0]

            try:
                #CONVERT ID TO NAME FOR DESTINATION
                endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                endpoint_end_url = "/?datasource=tranquility&language=en-us"
                endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url
                endpoint_response = urllib.urlopen(endpoint_final_url).read()
                endpoint_final_response = endpoint_response.split(
                    ":")[2].split(",")[0].replace('"', "")
                o_system = endpoint_final_response
            except:
                result.insert(
                    INSERT,
                    "\n" + "ERROR: Unable to get data from esi.evetech.net!")
                result.see("end")

            #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN
            return_route = create_route(True)
            return_distance = len(return_route.split(","))
            result.insert(
                INSERT, "\n" + "Including fixed end point: " +
                str(total_distance + return_distance) + "\n")
            result.see("end")

        try:
            cycles = int(iteration_field.get())
        except:
            cycles = 1
        count = 0
        while count < cycles:
            count += 1
            result.insert(INSERT, "\nCycle " + str(count) + ":\n")
            result.see("end")
            for route in routes:
                try:
                    #CONVERT ID TO NAME FOR ORIGIN
                    split_route = route.split(",")
                    origin = split_route[0].split("[")[1]
                    begin_url = "https://esi.evetech.net/latest/universe/systems/"
                    end_url = "/?datasource=tranquility&language=en-us"
                    final_url = begin_url + origin + end_url
                    response = urllib.urlopen(final_url).read()
                    final_origin = response.split(":")[2].split(
                        ",")[0].replace('"', "")
                    o_system = final_origin
                except:
                    result.insert(
                        INSERT, "\n" +
                        "ERROR: Unable to get data from esi.evetech.net!")
                    result.see("end")

                #ADD THE ORIGIN AS A DESTINATION SO IT'S NOT INCLUDED IN POTENTIAL ROUTES
                if initialized == False:
                    destinations.append(o_system)
                    initialized = True
                    last_destination = o_system

                #WHEN THE ROUTE IS CHANGED, THE PREVIOUS WAYPOINT MUST BE UPDATED
                elif o_system != last_destination:
                    o_system = last_destination

                #RESET THE BOOLEAN VALUES FOR ROUTE UPDATES
                optimized = False
                passed = False

                result.insert(
                    INSERT, "\n" + "Finding the shortest route from " +
                    o_system + " to another waypoint.\n")
                result.see("end")
                for waypoint in waypoints:
                    if o_system != waypoint and passed == False:  #PREVENT ROUTING TO THE CURRENT SYSTEM
                        d_system = waypoint
                        potential_route = create_route(
                            True
                        )  #CREATE A ROUTE TO GET THE LENGTH IN NUMBER OF JUMPS
                        split_pot = potential_route.split(",")
                        #FIND THE SHORTEST ROUTE FROM THE CURRENT LOCATION TO ANOTHER LOCATION IN THE LIST
                        if optimized == True:
                            split_best = best_route.split(",")
                            if d_system not in destinations and o_system not in origins and len(
                                    best_route
                            ) != 10000 and potential_route not in tested_routes:
                                result.insert(
                                    INSERT, "\nChecking route " +
                                    str(o_system) + " to " + str(d_system) +
                                    ": " + str(len(split_pot)) +
                                    " jumps. Best found: " +
                                    str(len(split_best)) + " jumps.")
                                result.see("end")
                            if len(split_pot) < len(
                                    split_best
                            ) and d_system not in destinations and o_system not in origins:
                                best_route = potential_route
                                sys1 = o_system
                                sys2 = d_system
                            elif len(split_pot) == len(
                                    split_best
                            ) and d_system not in destinations and o_system not in origins:
                                passed = True
                                optimized = False
                        else:
                            if len(split_pot) < len(
                                    last_route
                            ) and d_system not in destinations and o_system not in origins:
                                if d_system not in destinations and o_system not in origins and len(
                                        best_route
                                ) != 10000 and potential_route not in tested_routes:
                                    result.insert(
                                        INSERT,
                                        "\nChecking route " + str(o_system) +
                                        " to " + str(d_system) + ": " +
                                        str(len(split_pot)) +
                                        " jumps. Best found: " +
                                        str(len(last_route)) + " jumps.")
                                    result.see("end")
                                best_route = potential_route
                                sys1 = o_system
                                sys2 = d_system
                                optimized = True
                            elif len(split_pot) == len(
                                    last_route
                            ) and d_system not in destinations and o_system not in origins:
                                passed = True
                                optimized = False
                            else:
                                last_route = split_pot

                #OPTIMAL ROUTE WAS FOUND
                if optimized == True:
                    result.insert(
                        INSERT, "\n\n" + "Optimized route: " + sys1 + " to " +
                        sys2 + "\n")
                    result.see("end")
                    optimized_routes.append(best_route)
                    origins.append(sys1)
                    destinations.append(sys2)
                    last_destination = sys2

                #OPTIMAL ROUTE WAS NOT FOUND, SO THE NEXT WAYPOINT IN THE LIST IS USED
                elif optimized == False:
                    finished = False
                    for waypoint in waypoints:
                        if finished == False:
                            if o_system != waypoint and waypoint not in destinations:  #GET THE FIRST UNUSED WAYPOINT
                                d_system = waypoint
                                potential_route = create_route(True)
                                if potential_route not in tested_routes:  #THIS ROUTE HAS NOT YET BEEN EXAMINED
                                    tested_routes.append(potential_route)
                                    optimized_routes.append(potential_route)
                                    result.insert(
                                        INSERT, "\n\n" +
                                        "No exceptional route found. Creating route: "
                                        + o_system + " to " + d_system + "\n")
                                    result.see("end")
                                    origins.append(o_system)
                                    destinations.append(d_system)
                                    last_destination = d_system
                                    finished = True
                    if finished == False:  #ALL POSSIBLE ROUTES HAVE BEEN EXAMINED FOR THIS WAYPOINT SO THE SHORTEST ONE IS SELECTED
                        previous_best_route = [None] * 10000
                        best_tested_route = []
                        for route in tested_routes:
                            split_route = str(route).split(",")
                            origin = split_route[0].split("[")[1]
                            try:
                                o_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                                o_end_url = "/?datasource=tranquility&language=en-us"
                                o_final_url = o_begin_url + origin + o_end_url
                                o_response = urllib.urlopen(o_final_url).read()
                                o_final_response = o_response.split(
                                    ":")[2].split(",")[0].replace('"', "")
                            except:
                                result.insert(
                                    INSERT, "\n" +
                                    "ERROR: Unable to get data from esi.evetech.net!"
                                )
                                result.see("end")
                            if o_final_response == o_system:
                                if len(previous_best_route) != 10000:
                                    result.insert(
                                        INSERT, "\n" +
                                        "Comparing potential routes for this waypoint: "
                                        + str(len(split_route)) +
                                        " jumps VS " +
                                        str(len(previous_best_route)) +
                                        " jumps.")
                                    result.see("end")
                                s_destination = split_route[len(split_route) -
                                                            1].split("]")[0]
                                try:
                                    s_d_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                                    s_d_end_url = "/?datasource=tranquility&language=en-us"
                                    s_d_final_url = s_d_begin_url + s_destination + s_d_end_url
                                    s_d_response = urllib.urlopen(
                                        s_d_final_url).read()
                                    s_d_final_response = s_d_response.split(
                                        ":")[2].split(",")[0].replace('"', "")
                                except:
                                    result.insert(
                                        INSERT, "\n" +
                                        "ERROR: Unable to get data from esi.evetech.net!"
                                    )
                                    result.see("end")
                                if s_d_final_response not in destinations and len(
                                        split_route) < len(
                                            previous_best_route):
                                    best_tested_route = route
                                    previous_best_route = split_route

                        split_best_route = str(best_tested_route).split(",")
                        origin = split_best_route[0].split("[")[1]
                        destination = split_best_route[len(split_best_route) -
                                                       1].split("]")[0]
                        try:
                            o_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                            o_end_url = "/?datasource=tranquility&language=en-us"
                            o_final_url = o_begin_url + origin + o_end_url
                            o_response = urllib.urlopen(o_final_url).read()
                            t_o_final_response = o_response.split(
                                ":")[2].split(",")[0].replace('"', "")

                            d_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                            d_end_url = "/?datasource=tranquility&language=en-us"
                            d_final_url = d_begin_url + destination + d_end_url
                            d_response = urllib.urlopen(d_final_url).read()
                            t_d_final_response = d_response.split(
                                ":")[2].split(",")[0].replace('"', "")
                        except:
                            result.insert(
                                INSERT, "\n" +
                                "ERROR: Unable to get data from esi.evetech.net!"
                            )
                            result.see("end")
                        optimized_routes.append(best_tested_route)
                        result.insert(
                            INSERT, "\n\n" +
                            "All possible routes considered. Using route: " +
                            t_o_final_response + " to " + t_d_final_response +
                            "\n")
                        result.see("end")
                        origins.append(t_o_final_response)
                        destinations.append(t_d_final_response)
                        last_destination = t_d_final_response
                        finished = True

            total_routes.append(optimized_routes)
            previous_routes = optimized_routes
            optimized_routes = []
            origins = []
            destinations = []
            optimized = False
            initialized = False

        #SELECT THE BEST ROUTE FROM ALL CYCLES
        previous_best_distance = 10000
        for route in total_routes:
            total_route_distance = 0
            for r in route:
                s_r = r.split(",")
                total_route_distance += len(s_r)
            if previous_best_distance != 10000:
                result.insert(
                    INSERT, "\n" + "Comparing optimized routes: " +
                    str(total_route_distance) + " jumps VS " +
                    str(previous_best_distance) + " jumps.")
                result.see("end")
            if total_route_distance < previous_best_distance:
                final_best_route = route
                previous_best_distance = total_route_distance

        #DISPLAY THE OPTIMIZED ROUTE
        previous_destination = ""
        for route in final_best_route:
            split_route = str(route).split(",")
            origin = split_route[0].split("[")[1]
            destination = split_route[len(split_route) - 1].split("]")[0]

            #CONVERT THE ID TO NAME FOR EACH ROUTE
            try:
                o_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                o_end_url = "/?datasource=tranquility&language=en-us"
                o_final_url = o_begin_url + origin + o_end_url
                o_response = urllib.urlopen(o_final_url).read()
                o_final_response = o_response.split(":")[2].split(
                    ",")[0].replace('"', "")

                d_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                d_end_url = "/?datasource=tranquility&language=en-us"
                d_final_url = d_begin_url + destination + d_end_url
                d_response = urllib.urlopen(d_final_url).read()
                d_final_response = d_response.split(":")[2].split(
                    ",")[0].replace('"', "")

                #SET THE CURRENT SYSTEM TO INITIALIZE ITERATION
                if previous_destination == "":
                    previous_destination = o_final_response
                    result.insert(INSERT, "\n\n" + "New Route:" + "\n")
                    result.see("end")

                #SET THE CURRENT SYSTEM TO THE PREVIOUS DESTINATION
                if o_final_response == previous_destination:
                    final_routes.append(route)
                    previous_destination = d_final_response
                    result.insert(
                        INSERT,
                        "\n" + o_final_response + " to " + d_final_response)
                    result.see("end")
                else:  #THIS IS FOR DEBUGGING AND SHOULD NEVER HAPPEN
                    result.insert(
                        INSERT, "\n" + "ERROR: Out of order! " +
                        o_final_response + ":" + d_final_response)
                    result.see("end")
            except:
                result.insert(
                    INSERT,
                    "\n" + "ERROR: Unable to get data from esi.evetech.net!")
                result.see("end")

        #GET AND DISPLAY THE TOTAL TRIP DISTANCE IN NUMBER OF JUMPS
        total_distance = 0
        for route in final_routes:
            split_route = route.split(",")
            total_distance += len(split_route)
        result.insert(INSERT,
                      "\n\n" + "Number of jumps: " + str(total_distance))
        result.see("end")

        if fixed_endpoint == False:
            #GET THE ID FOR THE ORIGIN
            split_for_origin = final_routes[0].split(",")
            first_origin = split_for_origin[0].split("[")[1]

            #GET THE ID FOR THE LAST STOP
            final_route = final_routes[len(final_routes) - 1]
            split_final_route = final_route.split(",")
            last_stop = split_final_route[len(split_final_route) -
                                          1].split("]")[0]

            try:
                #CONVERT ID TO NAME FOR ORIGIN
                first_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                first_end_url = "/?datasource=tranquility&language=en-us"
                first_final_url = first_begin_url + first_origin + first_end_url
                first_response = urllib.urlopen(first_final_url).read()
                first_final_origin = first_response.split(":")[2].split(
                    ",")[0].replace('"', "")
                d_system = first_final_origin

                #CONVERT ID TO NAME FOR DESTINATION
                endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                endpoint_end_url = "/?datasource=tranquility&language=en-us"
                endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url
                endpoint_response = urllib.urlopen(endpoint_final_url).read()
                endpoint_final_response = endpoint_response.split(
                    ":")[2].split(",")[0].replace('"', "")
                o_system = endpoint_final_response
            except:
                result.insert(
                    INSERT,
                    "\n" + "ERROR: Unable to get data from esi.evetech.net!")
                result.see("end")

            #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN
            return_route = create_route(True)
            return_distance = len(return_route.split(","))
            result.insert(
                INSERT, "\n" + "Including return to origin: " +
                str(total_distance + return_distance) + "\n")
            result.see("end")
        else:
            #SET DESTINATION TO THE FIXED ENDPOINT
            d_system = fixed_endpoint_name

            #GET THE ID FOR THE LAST STOP
            final_route = final_routes[len(final_routes) - 1]
            split_final_route = final_route.split(",")
            last_stop = split_final_route[len(split_final_route) -
                                          1].split("]")[0]

            try:
                #CONVERT ID TO NAME FOR DESTINATION
                endpoint_begin_url = "https://esi.evetech.net/latest/universe/systems/"
                endpoint_end_url = "/?datasource=tranquility&language=en-us"
                endpoint_final_url = endpoint_begin_url + last_stop + endpoint_end_url
                endpoint_response = urllib.urlopen(endpoint_final_url).read()
                endpoint_final_response = endpoint_response.split(
                    ":")[2].split(",")[0].replace('"', "")
                o_system = endpoint_final_response
            except:
                result.insert(
                    INSERT,
                    "\n" + "ERROR: Unable to get data from esi.evetech.net!")
                result.see("end")

            #GET AND DISPLAY THE TOTAL TRIP DISTANCE INCLUDING RETURN TO ORIGIN
            return_route = create_route(True)
            return_distance = len(return_route.split(","))
            result.insert(
                INSERT, "\n" + "Including fixed end point: " +
                str(total_distance + return_distance) + "\n")
            result.see("end")

        #RESET VARIABLES SO ANOTHER SET OF WAYPOINTS CAN BE ENTERED
        previous_routes = []
        total_routes = []
        tested_routes = []
        final_best_route = []
        routes = []
        optimized_routes = []
        final_routes = []
        waypoints = []
        o_system = ""
        d_system = ""
        origins = []
        destinations = []
        initialized = False
        start_field.delete(0, 'end')
        end_field.delete(0, 'end')
        start_field.insert(0, "Origin")
        end_field.insert(0, "Destination")
        result.insert(INSERT, "\n")
        result.see("end")

    #START THE OPTIMIZATION THREAD
    def begin_optimization():
        global waypoint_adding_done
        if waypoint_adding_done == True:
            optimization_thread = threading.Thread(target=optimize)
            optimization_thread.start()

    #CHANGE THE ROUTE PREFERENCE
    def change_preference():
        global prefstr
        if preference.get() == 1:
            prefstr = "shortest"
        if preference.get() == 2:
            prefstr = "secure"
        if preference.get() == 3:
            prefstr = "insecure"

    #CHANGE THE FIXED ENDPOINT
    def set_fixed_endpoint():
        global fixed_endpoint_name
        global fixed_endpoint
        if fixed.get() == 1:
            fixed_endpoint = True
            fixed_end_field.configure(state=NORMAL)
        else:
            fixed_endpoint = False
            fixed_end_field.configure(state=DISABLED)

    #FINALIZE FIXED ENDPOINT
    def lock_fixed_endpoint(Event=None):
        global fixed_endpoint_name
        fixed_endpoint_name = fixed_end_field.get()
        fixed_end_field.configure(state=DISABLED)

    #SETUP BUTTONS
    fixed = IntVar()
    fixed_end_button = Checkbutton(window,
                                   text="Fixed End-Point",
                                   variable=fixed,
                                   command=set_fixed_endpoint,
                                   onvalue=1,
                                   offvalue=0,
                                   bg="gray",
                                   font=("Arial Bold", 12))
    fixed_end_button.pack()
    preference = IntVar()
    R1 = Radiobutton(window,
                     text="Shortest",
                     variable=preference,
                     value=1,
                     command=change_preference,
                     bg="gray",
                     font=("Arial Bold", 12))
    R1.pack()
    R2 = Radiobutton(window,
                     text="Secure",
                     variable=preference,
                     value=2,
                     command=change_preference,
                     bg="gray",
                     font=("Arial Bold", 12))
    R2.pack()
    R3 = Radiobutton(window,
                     text="Insecure",
                     variable=preference,
                     value=3,
                     command=change_preference,
                     bg="gray",
                     font=("Arial Bold", 12))
    R3.pack()
    button = Button(window,
                    text="Optimize",
                    font=("Arial Bold", 12),
                    bg="gray",
                    fg="blue",
                    command=begin_optimization)
    button.pack()
    end_field.bind(
        "<Return>", add_waypoint
    )  #ALLOWS THE RETURN KEY TO ADD A WAYPOINT INSTEAD OF CLICKING THE BUTTON
    fixed_end_field.bind("<Return>", lock_fixed_endpoint)
    window.mainloop()
Example #13
0
class FilePickEdit(Frame):
    def __init__(self,
                 master,
                 file_mask,
                 default_file,
                 edit_height=None,
                 user_onChange=None,
                 rename_on_edit=0,
                 font=None,
                 coloring=True,
                 allowNone=False,
                 highlighter=None,
                 directory='.'):
        '''
            file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"])
        '''
        self.master = master
        self.directory = directory
        self.user_onChange = user_onChange
        Frame.__init__(self, master)
        row = 0
        self.unmodified = True
        self.allowNone = allowNone
        self.file_extension = ""
        if type(file_mask) != list:
            file_mask = [file_mask]
        if "." in file_mask[0]:
            self.file_extension = file_mask[0][file_mask[0].rfind('.'):]
        # read filenames
        self.file_mask = file_mask
        self.updateList()
        # filename frame
        self.list_frame = Frame(self)
        self.list_frame.grid(row=row, column=0, sticky="WE")
        self.list_frame.columnconfigure(0, weight=1)
        # create list
        self.picked_name = StringVar(self)
        self.makelist()
        # refresh button
        self.refresh_button = Button(self.list_frame,
                                     text='<- refresh',
                                     command=self.refresh,
                                     height=1)
        self.refresh_button.grid(row=0, column=1, sticky='E')
        # save button
        self.save_button = Button(self.list_frame,
                                  text="save",
                                  command=self.save,
                                  height=1)
        self.save_button.grid(row=0, column=2, sticky="E")
        # editor
        row += 1
        if coloring:
            self.editor = SyntaxHighlightingText(self,
                                                 self.onEdit,
                                                 highlighter=highlighter)
        else:
            self.editor = ScrolledText2(self, self.onEdit)
        if font != None:
            self.editor.configure(font=font)
        if edit_height is not None:
            self.editor.configure(height=edit_height)
        self.editor.grid(row=row, column=0, sticky="NEWS")
        self.rowconfigure(row, weight=1)
        self.columnconfigure(0, weight=1)
        # option to change filename on edit
        row += 1
        self.options_frame = Frame(self)
        self.options_frame.grid(row=row, column=0, sticky=W)
        self.rename_on_edit = IntVar()
        self.cb = Checkbutton(self.options_frame,
                              text="rename on edit",
                              variable=self.rename_on_edit)
        self.cb.pack(side=LEFT)
        self.cb.configure(command=self.onChangeRename)
        self.rename_on_edit.set(rename_on_edit)
        # filename frame
        row += 1
        self.filename_frame = Frame(self)
        self.filename_frame.grid(row=row, column=0, sticky="WE")
        self.filename_frame.columnconfigure(0, weight=1)
        # save as filename
        self.save_name = StringVar(self)
        self.save_edit = Entry(self.filename_frame,
                               textvariable=self.save_name)
        self.save_edit.grid(row=0, column=0, sticky="WE")
        self.save_name.trace("w", self.onSaveChange)
        # pick default if applicableButton
        self.select(default_file)
        self.row = row

    def setDirectory(self, directory, keep=False):
        self.directory = directory
        self.updateList()
        self.makelist()
        #         menu = self.list["menu"] scrolledlist
        #         menu = self.list.listbox#["scrolledlist"]
        #         menu.delete(0, 'end')
        # add the new ones
        #         for filename in self.files:
        #             menu.add_command(label=filename, command=_setit(self.picked_name, filename, None))
        # if keep is true, only the files list will be updated but the content of the
        # text area will not be altered/removed
        if not keep: self.select("")

    def refresh(self):
        sel = self.get()
        self.updateList()
        self.select(sel, notify=False)

    def reloadFile(self):
        self.editor.delete("1.0", END)
        filename = self.picked_name.get()
        if os.path.exists(os.path.join(self.directory, filename)):
            new_text = file(os.path.join(self.directory, filename)).read()
            if new_text.strip() == "":
                new_text = "// %s is empty\n" % filename
            new_text = new_text.replace("\r", "")
        else:
            new_text = ""
        self.editor.insert(INSERT, new_text)

    def setText(self, txt):
        '''
        Replaces the text in the edit field as by typing
        into it.
        '''
        self.select("")
        if txt.strip() == "":
            txt = "// empty database\n"
        self.editor.insert(INSERT, txt)
        self.onEdit()

    def onSelChange(self, name, index=0, mode=0):
        self.reloadFile()
        filename = self.picked_name.get()
        self.save_name.set(filename)
        self.save_edit.configure(state=DISABLED)
        self.unmodified = True
        if self.user_onChange != None:
            self.user_onChange(filename)

    def onSaveChange(self, name, index, mode):
        pass

    #         if self.user_onChange != None:
    #             self.user_onChange(self.save_name.get())

    def autoRename(self):
        # modify "save as" name
        filename = self.picked_name.get()
        if filename == "":
            filename = "new" + self.file_extension  # if no file selected, create new filename
        ext = ""
        extpos = filename.rfind(".")
        if extpos != -1: ext = filename[extpos:]
        base = filename[:extpos]
        hpos = base.rfind("-")
        num = 0
        if hpos != -1:
            try:
                num = int(base[hpos + 1:])
                base = base[:hpos]
            except:
                pass
        while True:
            num += 1
            filename = "%s-%d%s" % (base, num, ext)
            if not os.path.exists(filename):
                break
        self.save_name.set(filename)
        # user callback
        if self.user_onChange != None:
            self.user_onChange(filename)

    def onEdit(self):
        if self.unmodified == True:
            self.unmodified = False
            # do auto rename if it's enabled or there is no file selected (editing new file)
            if self.rename_on_edit.get() == 1 or self.picked_name.get() == "":
                self.autoRename()
            # enable editing of save as name
            self.save_edit.configure(state=NORMAL)

    def onChangeRename(self):
        # called when clicking on "rename on edit" checkbox
        if self.rename_on_edit.get() == 1:
            if (not self.unmodified
                ) and self.save_name.get() == self.picked_name.get():
                self.autoRename()
        else:
            self.save_name.set(self.picked_name.get())

    def updateList(self):
        self.files = []
        if self.allowNone:
            self.files.append("")
        if os.path.exists(self.directory):
            for filename in os.listdir(self.directory):
                for fm in self.file_mask:
                    if fnmatch(filename, fm):
                        self.files.append(filename)
        self.files.sort()
        if len(self.files) == 0 and not self.allowNone:
            self.files.append("(no %s files found)" % str(self.file_mask))

    def select(self, filename, notify=True):
        ''' selects the item given by filename '''
        if filename in self.files:
            if not havePMW:
                self.picked_name.set(filename)
            else:
                self.list.selectitem(self.files.index(filename))
                if notify: self.onSelChange(filename)
        else:
            self.editor.delete("1.0", END)

    def makelist(self):
        if havePMW:
            self.list = Pmw.ComboBox(
                self.list_frame,
                selectioncommand=self.onSelChange,
                scrolledlist_items=self.files,
            )
            self.list.grid(row=0, column=0, padx=0, pady=0, sticky="NEWS")
            self.list.component('entryfield').component('entry').configure(
                state='readonly', relief='raised')
            self.picked_name = self.list
        else:
            self.list = apply(OptionMenu, (self.list_frame, self.picked_name) +
                              tuple(self.files))
            self.list.grid(row=0, column=0, sticky="NEW")
            self.picked_name.trace("w", self.onSelChange)

    def save(self):
        self.get()

    def set(self, selected_item):
        self.select(selected_item)

    def get(self):
        ''' gets the name of the currently selected file, saving it first if necessary '''
        filename = self.save_name.get()
        if self.unmodified == False:
            self.unmodified = True
            # save the file
            f = file(os.path.join(self.directory, filename), "w")
            f.write(self.editor.get("1.0", END).encode('utf-8'))
            f.close()
            # add it to the list of files
            #             if not filename in self.files:
            #                 self.files.append(filename)
            #                 self.files.sort()
            #                 self.list.destroy()
            #                 self.makelist()
            # set it as the new pick
            #if havePMW:
            #    self.picked_name.selectitem(self.files.index(filename), 1)
            #else:
            #    self.picked_name.set(filename)
            #             self.select(filename)
            self.refresh()
            self.select(filename, notify=False)
            self.save_edit.configure(state=DISABLED)
        return filename

    def get_text(self):
        return self.editor.get("1.0", END)

    def get_filename(self):
        return self.save_name.get()

    def set_enabled(self, state):
        self.editor.configure(state=state)
        if havePMW:
            self.list.component('entryfield_entry').configure(state=state)
            #             self.list.component('arrowbutton').configure(state=state)
            self.list.component('arrowbutton').bind(
                '<1>', (lambda a: 'break')
                if state == DISABLED else self.list._postList)
        else:
            self.list.configure(state=state)
        self.save_button.configure(state=state)
        self.cb.configure(state=state)
        self.save_edit.configure(state=state)
class File_Entry(Frame):
    ''' Quite self explanatoy...
    creates a row in which is possible to search for a file'''
    def __init__(self, master=None, **kwargs):
        # this was a nice frame, but considering that needs
        # from popup import FilePopUp, was moved elsewere
        # meaning this is not as low level as tk_lib

        #if not master and options.get('parent'):
        #    master = options['parent']
        self.master = master
        Frame.__init__(self, master)

        self.entries_txt = None
        self.entries_val = None

        if 'e_txt' in kwargs.keys():
            self.entries_txt = kwargs['e_txt']
        if 'e_val' in kwargs.keys():
            self.entries_val = kwargs['e_val']

        # File extension
        if 'f_ext' in kwargs.keys():
            self.file_ext = kwargs['f_ext']
        else:
            self.file_ext = [
                '.' + self.entries_val.split('.')[-1],
            ]
        # File extension description
        if 'f_ext_d' in kwargs.keys():
            self.fex_description = kwargs['f_ext_d']
        else:
            self.fex_description = [
                self.entries_txt,
            ]

        # file icon image, part of the master's personal library
        self.file_img = self.master.img['file']
        # inner class object container
        self._entry = []
        self._button = []
        self._strvar = StringVar()

        self.createWidgets()

    def createWidgets(self):
        '''creates the row content and stores the
           objects
        '''
        # INIT
        file_row = Frame(self)
        fi_text = self.entries_txt
        _def_file_ = self.entries_val
        f_ext_txt = ()
        for i in range(len(self.file_ext)):
            f_ext_txt += ((self.fex_description[i], self.file_ext[i]), )

        # Building
        _f_labels = format_dec([file_row, fi_text], _pack_=False)

        self._entry = Entry(file_row, width=13, textvariable=self._strvar)
        self._entry.insert('end', _def_file_)

        self._entry.bind("<Key>", lambda e: "break")  # Magic

        self._entry.xview_moveto(1)
        self._button = Button(
            file_row,
            image=self.file_img,
            command=(lambda El=self._entry: self.browsefile(El, f_ext_txt)))

        # Just packing
        format_dec(_f_labels, _create_=False)
        self._entry.pack(side='left', expand='yes', fill='x')
        self._button.pack(side='right', padx=0, pady=0)
        file_row.pack(side='top', fill='x', pady=3)

    def browsefile(self, entry, ext=None):
        '''Browse a file <button> action binder'''

        pop = FilePopUp(master=self)
        if ext <> None and isinstance(ext, tuple):
            #print '--- ', ext, type(ext)
            pop.filetypes['filetypes'] = ext  #(("All","*"),) #
        filepath = pop.getfilepath()

        try:
            fito = open(filepath, "r")
            fito.close()
            entry.delete(0, 'end')
            entry.insert(0, filepath)
            entry.xview_moveto(1)
        except:
            if filepath not in ['', ()]:
                print "Could not open File: ", filepath
                print exc_info()[1]

    def setter(self, value):

        if value:
            self.enable_entr()
        else:
            self.disable_entr()

    def disable_entr(self):
        self._entry.configure(state='disabled')
        self._button.configure(state='disabled')

    def enable_entr(self):
        self._entry.configure(state='normal')
        self._button.configure(state='normal')
Example #15
0
    def preUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=False)

        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(1, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.columnconfigure(10, pad=7)
        frame1.rowconfigure(5, weight=1)
        frame1.rowconfigure(5, pad=7)

        frame2.columnconfigure(8, pad=7, weight=1)
        frame2.rowconfigure(8, pad=7)

        lbl = Label(frame1, text="催化剂性质")
        lbl.grid(row=0, column=0, columnspan=8, rowspan=1, sticky=W, pady=4, padx=5)
        # K_Mat_Tree = ttk.Treeview(frame1)
        # K_Mat_Tree['show'] = 'headings'
        # K_Mat_Tree = self.makeMatrixUI(7, K_Mat_Tree, sourceDate.K_model)
        # K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=5, sticky=E + W + S + N, pady=4, padx=5)
        K_Mat_Tree = Text(frame1, height=18)
        self.makeMatrixUI(K_Mat_Tree, self.catObj)
        K_Mat_Tree.configure(state='normal')
        K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=6, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="优化方法:")
        lbl.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.optMethod)
        txt.configure(state='readonly')
        txt.grid(row=0, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="集总数:")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.n)
        txt.configure(state='readonly')
        txt.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="精确度:")
        lbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.tol)
        txt.configure(state='readonly')
        txt.grid(row=2, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        cateDetailButton = Button(frame1, text="查看催化剂详情")
        cateDetailButton.grid(row=3, column=8)
        # ________________________________________
        lbl = Label(frame2, text="待预测条件")
        lbl.grid(row=0, column=0, sticky=W, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度(K)")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)
        if not self.catObj.withTemp:
            self.T_input.insert(0, self.catObj.t)
            self.T_input.configure(state='readonly')
        self.T_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力(KPa)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比")
        lbl.grid(row=4, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=4, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="停留时间(s)")
        lbl.grid(row=5, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=5, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=6, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=7, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=7, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="微分方程步长")
        lbl.grid(row=8, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.step_input = Entry(frame2)
        self.step_input.insert(0, 0.1)
        self.step_input.grid(row=8, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)
        self.preResult_LB = Listbox(frame2)
        self.preResult_LB.grid(row=1, column=7, columnspan=2, rowspan=6, pady=4, padx=5)

        cateDetailButton = Button(frame2, text="预测", command=self.doPre)
        cateDetailButton.grid(row=8, column=7, columnspan=2)
Example #16
0
def setupMoveSection():
    global defaultWidth, defaultHeight
    global buttonWidth, buttonHeight, buttonBGColor, buttonFGColor
    global stage1Entry, stage2Entry, stage3Entry, stage4Entry
    global moveAllRelativeButton, moveAllAbsoluteButton
    global divisions

    moveLabel = Label(rFrame,
                      text="Move Commands",
                      font=("Times New Roman", 16),
                      wraplength=200,
                      bg="white")
    moveLabel.place(relx=.5,
                    rely=1.0 / divisions,
                    anchor="c",
                    relwidth=buttonWidth,
                    relheight=buttonHeight)

    stageEntryFrame = Frame(rFrame, width=buttonWidth, bg="white")
    stageEntryFrame.place(relx=.5, rely=7.0 / divisions, anchor="c")

    stage1Label = Label(stageEntryFrame,
                        text="Slide Mouse in",
                        bg="white",
                        fg="black",
                        font=("Times New Roman", 12))
    stage1Label.grid(row=0, columnspan=2)

    stage1Entry = Entry(stageEntryFrame,
                        font=("Times New Roman", 12),
                        width=15)
    stage1Entry.grid(row=1, column=0)
    stage1Entry.configure(state=DISABLED)

    stage1Units = Label(stageEntryFrame,
                        text="mm",
                        anchor=W,
                        bg="white",
                        fg="black",
                        font=("Times New Roman", 12))
    stage1Units.grid(row=1, column=1)

    stage2Label = Label(stageEntryFrame,
                        text="Rotation about Axis",
                        bg="white",
                        fg="black",
                        font=("Times New Roman", 12))
    stage2Label.grid(row=2, columnspan=2)

    stage2Entry = Entry(stageEntryFrame,
                        font=("Times New Roman", 12),
                        width=15)
    stage2Entry.grid(row=3, column=0)
    stage2Entry.configure(state=DISABLED)

    stage2Units = Label(stageEntryFrame,
                        text="degrees",
                        anchor=W,
                        bg="white",
                        fg="black",
                        font=("Times New Roman", 12))
    stage2Units.grid(row=3, column=1)

    stage3Label = Label(stageEntryFrame,
                        text="Rotary Axis Y-point",
                        bg="white",
                        fg="black",
                        font=("Times New Roman", 12))
    stage3Label.grid(row=4, columnspan=2)

    stage3Entry = Entry(stageEntryFrame,
                        font=("Times New Roman", 12),
                        width=15)
    stage3Entry.grid(row=5, column=0)
    stage3Entry.configure(state=DISABLED)

    stage3Units = Label(stageEntryFrame,
                        text="mm",
                        anchor=W,
                        bg="white",
                        fg="black",
                        font=("Times New Roman", 12))
    stage3Units.grid(row=5, column=1)

    stage4Label = Label(stageEntryFrame,
                        text="Rotary Axis X-point",
                        bg="white",
                        fg="black",
                        font=("Times New Roman", 12))
    stage4Label.grid(row=6, columnspan=2)

    stage4Entry = Entry(stageEntryFrame,
                        font=("Times New Roman", 12),
                        width=15)
    stage4Entry.grid(row=7, column=0)
    stage4Entry.configure(state=DISABLED)

    stage4Units = Label(stageEntryFrame,
                        text="mm",
                        anchor=W,
                        bg="white",
                        fg="black",
                        font=("Times New Roman", 12))
    stage4Units.grid(row=7, column=1)

    moveAllRelativeButton = Button(rFrame,
                                   text="Move All Stages Relative",
                                   bg=buttonBGColor,
                                   fg=buttonFGColor,
                                   command=moveAllRelative)
    moveAllRelativeButton.place(relx=.5,
                                rely=13.0 / divisions,
                                relwidth=buttonWidth,
                                relheight=buttonHeight,
                                anchor="c")
    moveAllRelativeButton.configure(state=DISABLED)

    moveAllAbsoluteButton = Button(rFrame,
                                   text="Move All Stages Absolute",
                                   bg=buttonBGColor,
                                   fg=buttonFGColor,
                                   command=moveAllAbsolute)
    moveAllAbsoluteButton.place(relx=.5,
                                rely=15.0 / divisions,
                                relwidth=buttonWidth,
                                relheight=buttonHeight,
                                anchor="c")
    moveAllAbsoluteButton.configure(state=DISABLED)
    return
    def __init__(self):
        window = Tk()
        window.title('Scientific Calculator')
        window.configure(background="white")
        self.string = StringVar()
        entry = Entry(window, textvariable=self.string)
        entry.grid(row=0, column=0, columnspan=6)
        entry.configure(background="white")
        entry.focus()

        values = [
            "7", "8", "9", "/", "%", "clear", "AC", "4", "5", "6", "*", "(",
            ")", "**", "1", "2", "3", "-", "=", ",", "0", ".", "min", "+",
            "sin", "asin", "cos", "acos", "tan()", "pow", "log10", "max",
            "abs", "floor", "pi", "e", "log", "ceil", "degrees", "radians"
        ]
        text = 1
        i = 0
        row = 1
        col = 0
        for txt in values:
            padx = 10
            pady = 10
            if (i == 7):
                row = 2
                col = 0
            if (i == 14):
                row = 3
                col = 0
            if (i == 19):
                row = 4
                col = 0
            if (i == 26):
                row = 5
                col = 0
            if (i == 33):
                row = 6
                col = 0
            if (txt == '='):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=70,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.equals())
                btn.grid(row=row, column=col, columnspan=3, padx=2, pady=2)
                btn.configure(background="yellow")

            elif (txt == 'clear'):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.delete())
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="grey")
            elif (txt == 'AC'):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.clearall())
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="red")
            else:
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.addChar(txt))
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="cyan")

            col = col + 1
            i = i + 1
        window.mainloop()
Example #18
0
class Main():

	def __init__(self, master):

		#La intro se puede apagar al final, cumple solo una funcion vistosa

		#Iniciacion propia de la ventan y sus configuraciones
		self.master=master
		self.master.wm_title(R.AppTitle)
		self.widht=(self.master.winfo_screenwidth() - self.master.winfo_reqwidth()) / 2
		self.height=(self.master.winfo_screenheight() - self.master.winfo_reqheight()) / 2
		self.master.geometry("+{0:.0f}+{1:.0f}".format(self.widht, self.height))
		self.master.deiconify()
		self.master.resizable(False,False)
		self.icon=(R.IconPath)
		self.master.iconbitmap(self.icon)
		self.master.configure(background=R.Bgcolor)

		#Definicion de variables variables que estaran en uso.
		self.btnFlecha=Image.open(R.BtnFlechaImgPath)
		self.btnFlechaimg=ImageTk.PhotoImage(self.btnFlecha)
		self.selectMed = StringVar(self.master)
		self.selectMed.set(R.SelectMed)

		#Las variables que usaran para saber que hacer o que reemplazar
		self.fromLabel = StringVar()
		self.fromLabel.set(R.Select)
		self.toLabel=StringVar()
		self.toLabel.set(R.Select)

		#Los valores de las entradas
		self.fromNumber=StringVar()
		self.toNumber=StringVar()

		#La creacion de las partes del programita.
		self.menuChoices()
		self.convertChoice()
		self.convertButton()

	def menuChoices(self):

		#Menu de seleccion principal sobre los tipos que conversion que hara el programa
		self.MenuChoices = OptionMenu(self.master, self.selectMed, R.LongMain,R.AlmacMain, command=self.choice)
		self.MenuChoices.configure(bg="white",fg="black",activebackground="#eceefb",highlightbackground=R.Bgcolor,
									indicatoron=0,image=self.btnFlechaimg,compound='right')
		self.MenuChoices.grid(row=0,column=0)

	def convertChoice(self):

		#Las partes que integran el primer submenu llamado "DE", labelFrame,menu, entrada.
		self.labelFrameFrom=LabelFrame(self.master,text="De",background=R.Bgcolor)
		self.labelFrameFrom.grid(row=1,column=0,padx=5,pady=3)

		self.menuFrom=OptionMenu(self.labelFrameFrom,self.fromLabel,"",)
		self.menuFrom.configure(bg=R.White,fg=R.Black,activebackground=R.hoverBtnColor,highlightbackground=R.Bgcolor,
								indicatoron=0,image=self.btnFlechaimg, compound='right')
		self.menuFrom.grid(row=0,column=0,padx=3,pady=2,sticky=E)

		self.entryFrom=Entry(self.labelFrameFrom,justify='center',textvariable=self.fromNumber)
		self.entryFrom.grid(row=2,column=0,padx=5,pady=5)

		#Las partes que integran el segundo submenu llamado "Hasta", labelFrame, menu, entrada.

		self.labelFrameTo=LabelFrame(self.master,text="Hacia",background=R.Bgcolor)
		self.labelFrameTo.grid(row=1,column=1,padx=5,pady=3)

		self.menuTo=OptionMenu(self.labelFrameTo,self.toLabel,"",)
		self.menuTo.configure(bg=R.White,fg=R.Black, activebackground=R.hoverBtnColor,highlightbackground=R.Bgcolor,
					indicatoron=0,image=self.btnFlechaimg, compound='right')
		self.menuTo.grid(row=0,column=0, padx=3, pady=2, sticky=E)

		self.entryTo=Entry(self.labelFrameTo,justify='center',textvariable=self.toNumber,state="readonly")
		self.entryTo.configure(bg="red", readonlybackground=R.Bgcolor)
		self.entryTo.grid(row=2,column=0,padx=3,pady=5)

	def convertButton(self):
		#El boton Convertir que activa las funcionalidades de los campos
		self.butonimgpath = Image.open(R.BtnConvertirImgPath)
		self.butonTkImage = ImageTk.PhotoImage(self.butonimgpath)
		self.button = Button(self.master,text='Convertir',command=self.choiceFromTo)
		self.button.configure(image=self.butonTkImage, bd=False, highlightthickness=0, activebackground="black")
		self.button.grid(row=3,column=1,sticky=E)

	def choice(self, choices):
		#Al tocar el boton [<- Selecione] se cambia la opcion de medida y se genera opciones acorde
		# error.set("")
		#Opciones acorde en el caso de elegir "Longitudes"
		if choices==R.LongMain:
				self.fromLabel.set(R.LongStart)
				self.toLabel.set(R.LongStart)
				self.clean()
				# medidas= ("kms", "milla","metro","legua","yarda","pie")
				for m in R.LongList:
						self.menuFrom['menu'].add_command(label=m,command=lambda v=self.fromLabel,l=m:v.set(l))
				for m in R.LongList:
						self.menuTo['menu'].add_command(label=m,command=lambda v=self.toLabel,l=m:v.set(l))

		#Genera las opciones si se elige "Almacenamientos"
		elif choices==R.AlmacMain:
				self.fromLabel.set(R.AlmacStart)
				self.toLabel.set(R.AlmacStart)
				self.clean()
				# medidas= ("Gbs", "Mbs","Kbs","bytes")
				for m in R.AlmacList:
						self.menuFrom['menu'].add_command(label=m,command=lambda v=self.fromLabel,l=m:v.set(l))
				for m in R.AlmacList:
						self.menuTo['menu'].add_command(label=m,command=lambda v=self.toLabel,l=m:v.set(l))

	def choiceFromTo(self):
		
		try:
			#Se toma los valores de las seleciones [DE] y [HACIA], ademas de la entrada numerica
			# self.fromChoice=self.fromNumber.get()
			self.fromChoice=self.fromLabel.get()
			self.toChoice=self.toLabel.get()
			self.fromN=self.entryFrom.get()

			#A partir de un if se consulta
			#el objeto a crear que poseen los comportamientos de convertirse a 
			#otra medida

			#Si la medida esta en el campo de las longitudes
			if self.toChoice in R.LongList:
				convLong = Distancia(float(self.fromN))
				dicChoices = {0: convLong.km_a_(self.toChoice),
				 					1: convLong.milla_a_(self.toChoice),
			 	 					2: convLong.metro_a_(self.toChoice),
		 	 	 					3: convLong.legua_a_(self.toChoice),
	 	 	 	 					4: convLong.yarda_a_(self.toChoice),
 	 	 	 	 					5: convLong.pie_a_(self.toChoice)}

				self.toNumber.set(dicChoices.get(R.LongList.index(self.fromChoice)))

			#Si la medida esta en el campo de las medidas de almacenamiento
			elif self.toChoice in R.AlmacList:
				conAlmc = Almacenamiento(float(self.fromN))
				dicChoices = {0: conAlmc.gb_a_(self.toChoice),
								1: conAlmc.mb_a_(self.toChoice),
								2: conAlmc.kbs_a_(self.toChoice),
								3: conAlmc.bytes_a_(self.toChoice)}
				
				self.toNumber.set(dicChoices.get(R.AlmacList.index(self.fromChoice)))

		except:
			self.toNumber.set('{}'.format("Numero no valido"))


	def clean(self):
		self.menuTo['menu'].delete(0,END)
		self.menuFrom['menu'].delete(0,END)
class App:
    def __init__(self, master):
        self.master = master
        column0_padx = 24
        row_pady = 40
        self.imgck = IntVar()
        self.latck = IntVar()
        self.lonck = IntVar()
        self.timeck = IntVar()
        self.dateck = IntVar()
        self.datestate = int()
        self.imgval = StringVar()
        self.latval = StringVar()
        self.lonval = StringVar()
        self.timeval = StringVar()
        self.dateval = StringVar()
        self.headerVal = IntVar()
        self.rbv = IntVar()
        vcmd = (master.register(self.validate), '%d', '%i', '%P', '%s',
                '%S', '%v', '%V', '%W')

        self.entryExif = Entry(master, relief="sunken")
        self.entryExif.insert(0, "EXIF csv file")
        self.entryExif.grid(row=0,columnspan=4, sticky='EW',padx=5, pady=10)
        exifbtn = Button(master, text="OPEN CSV file", command=self.getEXIFfile)
        exifbtn.grid(row=1, column=0, padx=5, sticky='w')

        ##added to allow header line
        self.headerOpt = Checkbutton(master, text="Select if CSV file has header line", variable=self.headerVal)
        self.headerOpt.grid(row=2, column=0, padx=5, sticky='w')

        self.entryJPGS = Entry(master, relief="sunken")
        self.entryJPGS.insert(0, "JPEG folder")
        self.entryJPGS.grid(row=3,columnspan=4, sticky='EW',padx=5, pady=10)
        JPGbtn = Button(master, text="OPEN JPEG folder", command=self.getJPEGFolder)
        JPGbtn.grid(row=4, column=0, padx=5, sticky='w')

        self.paramFile = Entry(master, relief="sunken")
        self.paramFile.insert(0, "Param file")
        self.paramFile.grid(row=5, columnspan=4, sticky='EW', padx=5, pady=10)
        parambtn = Button(master, text="OPEN PARAM file", command=self.getParamfile)
        parambtn.grid(row=6, column=0, padx=5, sticky='w')

        
        lbl_exiftag = Label(master, text="EXIF tag", wraplength=100,
                            anchor='w', justify='left')
        lbl_column = Label(master, text="CSV column (zero based)", wraplength=100,
                           anchor='w', justify='left')
        cbImage = Checkbutton(master, text='Image name', variable=self.imgck,
                              command=self.imgcheck)
        cbLatitude = Checkbutton(master, text='Latitude', variable=self.latck,
                                 command=self.latcheck)
        cbLongitude = Checkbutton(master, text='Longitude', variable=self.lonck,
                                  command=self.loncheck)
        cbTime = Checkbutton(master, text='GPSTime', variable=self.timeck,
                             command=self.timecheck)
        cbDate = Checkbutton(master, text='GPSDate', variable=self.dateck,
                             command=self.datecheck)
        lblText =Label(master, text="Free text fields:")
        lblArtist = Label(master, text="Artist:")
        
##        lbl_analysis = Label(master, text="Analysis Library")
        self.entryImage = Entry(master, validate = 'key', validatecommand = vcmd,
                                width=5, state='disabled')
        self.entryLat = Entry(master, validate = 'key', validatecommand = vcmd,
                              width=5, state='disabled')
        self.entryLon = Entry(master, validate = 'key', validatecommand = vcmd,
                              width=5, state='disabled')
        self.entryTime = Entry(master, validate = 'key', validatecommand = vcmd,
                               width=5, state='disabled')
        self.entryDate = Entry(master, validate = 'key', validatecommand = vcmd,
                               width=5, state='disabled')
        self.entryArtist = Entry(master, width=40)

        #lbl_testcase_exec.grid(row=0, column=2, padx=20, pady=12, sticky='w')
        lbl_exiftag.grid(row=7, column=0, padx=20, pady=12, sticky='w')
        lbl_column.grid(row=7, column=1, padx=10, pady=12, sticky='w')
        cbImage.grid(row=8, column=0, padx=20, sticky='w')
        cbLatitude.grid(row=9, column=0, padx=20, sticky='w')
        cbLongitude.grid(row=10, column=0, padx=20, sticky='w')
        cbTime.grid(row=11, column=0, padx=20, sticky='w')
        cbDate.grid(row=12, column=0, padx=20, sticky='w')
        lblText.grid(row=13, column=0, padx=30, sticky='w')
        lblArtist.grid(row=14, column=0, padx=20, sticky='w')
        self.entryImage.grid(row=8, column=1, padx=10, sticky='w')
        self.entryLat.grid(row=9, column=1, padx=10, sticky='w')
        self.entryLon.grid(row=10, column=1, padx=10, sticky='w')
        self.entryTime.grid(row=11, column=1, padx=10, sticky='w')
        self.entryDate.grid(row=12, column=1, padx=10, sticky='w')
        lbl_datefmt = Label(master, text="Select date format:", wraplength=500,
                           anchor='w', justify='left')
        lbl_datefmt.grid(row=12, column=1, padx=50, sticky='w')
        self.entryArtist.grid(row=14, column=1, padx=10, sticky='w')
##        ##added to allow header line
##        self.dateOpt1 = Checkbutton(master, text="YYYYMMDD", variable=self.headerVal)
##        self.dateOpt1.grid(row=10, column=1, padx=160, sticky='w')
##        self.dateOpt2 = Checkbutton(master, text="YYYY:MM:DD", variable=self.headerVal)
##        self.dateOpt2.grid(row=10, column=1, padx=260, sticky='w')
##        self.dateOpt3 = Checkbutton(master, text="MM/DD/YYYY", variable=self.headerVal)
##        self.dateOpt3.grid(row=10, column=1, padx=360, sticky='w')        

        #try radio buttons
        Radiobutton(master, text="YYYYMMDD", variable=self.rbv, value=1, command=self.rdioInvoke).grid(row=11, column=1, padx=190, sticky='w')
        Radiobutton(master, text="YYYY:MM:DD", variable=self.rbv, value=2).grid(row=12, column=1, padx=190, sticky='w')
        Radiobutton(master, text="MM/DD/YYYY", variable=self.rbv, value=3).grid(row=13, column=1, padx=190, sticky='w')

        # buttons
        bottom_frame = Frame(master)
        bottom_frame.grid(row=30, column=1, columnspan=3, sticky='w')

        #I had to add the self to the prefix, otherwise my rdioInvoke wouldn't work.
        #I'm guessing the self is sort of the global aspect.
        #temporarily commenting this out so I can just test reading the param file
        self.btn_start = Button(bottom_frame, text = "Submit", width=7, command=self.MergeExif)
        #self.btn_start = Button(bottom_frame, text = "Submit", width=7, command=self.readParamfile)
        self.btn_start.pack(side='left', pady=20)
        self.btn_start.config(state='disabled')
##        btn_commit = Button(bottom_frame, text="Commit", width=7)
##        btn_commit.pack(side='left', padx=80)
        btn_exit = Button(bottom_frame, text="Exit", width=7, command=self.cbtnClick)
        btn_exit.pack(side='left', padx=10)

    def rdioInvoke(self):
        print "rdioInvoke"
        self.btn_start.configure(state='normal')
        
    def cbtnClick(self):
        print "close button event handler"
        self.master.destroy()

    def imgcheck(self):
        print "check"
        if self.imgck.get() == 0:
            self.entryImage.configure(state='disabled')
        else:
            self.entryImage.configure(state='normal')
    def latcheck(self):
        print "check"
        if self.latck.get() == 0:
            self.entryLat.configure(state='disabled')
        else:
            self.entryLat.configure(state='normal')            
    def loncheck(self):
        print "check"
        if self.lonck.get() == 0:
            self.entryLon.configure(state='disabled')
        else:
            self.entryLon.configure(state='normal')
    def timecheck(self):
        print "check"
        if self.timeck.get() == 0:
            self.entryTime.configure(state='disabled')
        else:
            self.entryTime.configure(state='normal')
    def datecheck(self):
        print "check"
        if self.dateck.get() == 0:
            self.entryDate.configure(state='disabled')
        else:
            self.entryDate.configure(state='normal')
            #self.datestate == 1
    def validate(self, action, index, value_if_allowed,
                 prior_value, text, validation_type, trigger_type, widget_name):
        if text in '0123456789':
            return True
        else:
            return False
    def getEXIFfile(self):
        EXIFcsvfile = tkFileDialog.askopenfilename(title='Image EXIF CSV file')
        #need to fix the next line
        self.entryExif.delete(0,END)
        if len(EXIFcsvfile) > 0:
            self.entryExif.insert(0,EXIFcsvfile)
            
    def getJPEGFolder(self):
        #by not specifying an intial directory, it starts where the script is located.
        JPGfolder = tkFileDialog.askdirectory(title='Pick JPEG folder')
        #need to clear anything that's there
        self.entryJPGS.delete(0,END)
        if len(JPGfolder) > 0:
            #print "now read JPEG folder %s" % JPGfolder
            #for entry widget
            self.entryJPGS.insert(0,JPGfolder)

    def getParamfile(self):
        PARAMtxtfile = tkFileDialog.askopenfilename(title='Paramter text file')
        self.paramFile.delete(0,END)
        if len(PARAMtxtfile) > 0:
            self.paramFile.insert(0,PARAMtxtfile)

    def readParamfile(self):
        params = self.paramFile.get()
        inputparams = open(params, "r")
        allparams = inputparams.read()
        for cmd3 in allparams.splitlines():
            if "-comment" in cmd3:
##                print cmd3
##                print " "
                val3 = cmd3
        for cmd4 in allparams.splitlines():
            if "-sep" in cmd4:
##                print cmd4
##                print " "
                #return cmd4
                val4 = cmd4

        for cmd6 in allparams.splitlines():
            if "-Caption=" in cmd6:
##                print cmd6
##                print " "
                #return cmd6
                val6=cmd6

        for cmd9 in allparams.splitlines():
            if "-Caption-Abstract" in cmd9:
##                print cmd9
##                print " "
                #return cmd9
                val9 = cmd9

        for cmd10 in allparams.splitlines():
            if "-ImageDescription=" in cmd10:
##                print cmd10
##                print " "
                #return cmd10
                val10 = cmd10
##        print "read params"
##        print "val3"
##        print val3
        return (val3, val4, val6, val9, val10)
    
        #self.MergeExif()
        
            
    def MergeExif(self):
        try:
            test = self.entryExif.get()
            print test

##            print "date format"
##            print str(self.rbv.get())
            inputfile = open(test, "r")
            #print "made it here 1"
            imgval = int(self.entryImage.get())
            #print self.entryImage.get()
            #print str(imgval)
            if self.latck.get() <> 0:
                latval = int(self.entryLat.get())
            #print "made it here 1a"
            if self.lonck.get() <> 0:
                lonval = int(self.entryLon.get())
            print "made it here 1b"
            if self.timeck.get() <> 0:
                timeval = int(self.entryTime.get())
            print "made it here 1c"
            if self.dateck.get() <> 0:
                dateval = int(self.entryDate.get())
                print "got date"
                print str(dateval)
            print "made it here 2"
            ##add this if statement to deal with header value
            if self.headerVal.get() == 1:
                print "have a header value"
                line = inputfile.readline()
            else:
                print "no header value"
            print "getting return"
##            retcmd3, retcmd4, retcmd6, retcmd9, retcmd10 = self.readParamfile()
##            print "just cmd3"
##            print retcmd3
            allreturns = self.readParamfile()
            print "allreturns"
            print allreturns
##            print "first return"
##            print allreturns[0]
            while 1:
                line = inputfile.readline()
                print "made it here 3"
                values = str.split(line,",")
##                print line
##                print "imgval"
##                print imgval
                ##if extension is included in text file
                img = values[imgval].strip()
                ##if extension is NOT included in text file
                ##img = values[imgval].strip() + '.JPG'
                vlat = values[latval].strip()
                vlon = values[lonval].strip()
                ingpsdate = values[dateval].strip()
##                #section to read date formats
                if self.rbv.get()==1:
                    vyr=str(ingpsdate)[0:4]
                    vmm=str(ingpsdate)[4:6]
                    vdd=str(ingpsdate)[6:8]
                    vgpsdate=vyr+":"+vmm+":"+vdd
                if self.rbv.get()==2:
                    vgpsdate=ingpsdate
                if self.rbv.get()==3:
                    vmm, vdd, vyr = ingpsdate.split("/")
                    if len(vmm)==1:
                        vmm="0"+vmm
                    if len(vdd)==1:
                        vdd="0"+vdd
                    vgpsdate=vyr+":"+vmm+":"+vdd                    
##                if ingpsdate.find(':')==-1:
##                    vyr=str(ingpsdate)[0:4]
##                    vmm=str(ingpsdate)[4:6]
####                    print ingpsdate
####                    print "year"
####                    print vyr
####                    print "month"
####                    print vmm
##                    vdd=ingpsdate[6:8]
##                    vgpsdate=vyr+":"+vmm+":"+vdd
##                else:
##                    vgpsdate=ingpsdate
                print vgpsdate
                vgpstime = values[timeval].strip()
                imagefolder = self.entryJPGS.get()
                fullimg = os.path.join(imagefolder, img)
                fullimg = fullimg.replace('\\','/')
                vartist = self.entryArtist.get()
                vartistquotes = '"'+vartist+'"'
##                print str(fullimg)                
##                print str(vlat)
##                print str(vlon)
##                print str(vgpsdate)
##                print str(vgpstime)
                if (float(vlat)) > 0:
                    print "latref1"
                    vlatref = 'N'
                else:
                    print "latref2"
                    vlatref = 'S'
                if (float(vlon)) > 0:
                    vlonref = 'E'
                else:
                    vlonref = 'W'
##                print str(vlatref)
##                print str(vlonref)
                cmd = "exiftool -GPSDateStamp=" + vgpsdate + " -GPSTimeStamp="+vgpstime+" -GPSLatitude="+vlat+" -GPSLatitudeRef="+ vlatref+\
                      " -GPSLongitude="+vlon+" -GPSLongitudeRef="+vlonref+" "+ " -Artist=" +vartistquotes +" "+fullimg
                print cmd
                #print "made it past first os.system"
                subprocess.check_call(cmd, shell=True)
                print "executed"
                cmd2 = """exiftool -Credit="U.S. Geological Survey" -Contact="[email protected] " """+ fullimg
                subprocess.check_call(cmd2, shell=True)

                #jpeg comment
                print "in command 3 section"
                cmd3=allreturns[0]
                cmd3new = cmd3+" "+fullimg
                print cmd3new
                #print cmd3
                #cmd3 = """exiftool -comment="Photo from down-looking camera on the USGS SEABOSS deployed from the R/V Rafael during survey 2012-003-FA (http://woodshole.er.usgs.gov/operations/ia/public_ds_info.php?fa=2012-003-FA). Released as part of publication DOI:10.3133/ds937. " """+ fullimg
                subprocess.check_call(cmd3new, shell=True)
                #iptc info
                #cmd4 = """exiftool -sep ", " -keywords="Barnegat Bay, New Jersey, 2012-003-FA, SEABOSS, sea floor, USGS " """+ fullimg
                cmd4=allreturns[1]
                cmd4new = cmd4+" "+fullimg
                #subprocess.check_call(cmd4, shell=True)
                subprocess.check_call(cmd4new, shell=True)
                #cmd5 unused and skipped

                #xmp info
                #cmd6 = """exiftool -Caption="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg
                cmd6=allreturns[2]
                cmd6new = cmd6+" "+fullimg                
                #subprocess.check_call(cmd6, shell=True)
                subprocess.check_call(cmd6new, shell=True)
                print "did caption"
                #EXIF info
                cmd7 = """exiftool -Copyright="Public Domain - please credit U.S. Geological Survey " """ + fullimg
                subprocess.check_call(cmd7, shell=True)
                print "did copyright"
                #iptc info
                cmd8 = """exiftool -CopyrightNotice="Public Domain - please credit U.S. Geological Survey " """ + fullimg
                subprocess.check_call(cmd8, shell=True)
                #iptc info
                #cmd9 = """exiftool -Caption-Abstract="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg
                cmd9=allreturns[3]
                cmd9new = cmd9+" "+fullimg                 
                #subprocess.check_call(cmd9, shell=True)
                subprocess.check_call(cmd9new, shell=True)
                #exif info - software such as Picasso use this as the caption
                #cmd10 = """exiftool -ImageDescription="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg                
                cmd10=allreturns[4]
                cmd10new = cmd10+" "+fullimg                
                #subprocess.check_call(cmd10, shell=True)
                subprocess.check_call(cmd10new, shell=True)
        except:
            print "booboo maybe?"
        inputfile.close()
        print "done"
Example #20
0
class editPool(Frame):

    font_decorations = ('italic', 'bold', 'subscript', 'superscript')
    font_decorations_to_names = {
        'italic': _('italic'),
        'bold': _('bold'),
        'subscript': _('subscript'),
        'superscript': _('superscript')
    }
    font_decorations_to_html = {
        'italic': 'i',
        'bold': 'b',
        'subscript': 'sub',
        'superscript': 'sup'
    }

    def __init__(self, master, buttons=('interpret', 'asis'), **kw):
        Frame.__init__(self, master, **kw)
        self.text = ''
        self.interpret = 1
        self.editPool = Entry(self,
                              width=50,
                              state='disabled',
                              font="Helvetica 12")
        self.editPool.pack(side='left')

        self.editPool.bind('<Return>', self._interpretButtonPressed)
        self.editPool.bind('<Escape>', self._cancel)

        self.editPool.bind('<Control-s>', lambda e: self._tag_it("sub"))
        self.editPool.bind('<Control-S>', lambda e: self._tag_it("sup"))
        self.editPool.bind('<Control-i>', lambda e: self._tag_it("i"))
        self.editPool.bind('<Control-b>', lambda e: self._tag_it("b"))

        self.editPool.bind("<KeyPress>", self._key)

        if 'interpret' in buttons:
            pix = Store.app.request('pixmap', name='interpret')
            self.interpretButton = Button(self,
                                          text=_('Interpret'),
                                          image=pix,
                                          command=self._interpretButtonPressed,
                                          state='disabled',
                                          bd=config.border_width)
            Store.app.balloon.bind(self.interpretButton,
                                   _('Interpret text (where applicable)'))
            self.interpretButton.pack(side='left')
        else:
            self.interpretButton = None

        if 'asis' in buttons:
            pix = Store.app.request('pixmap', name='asis')
            self.setButton = Button(self,
                                    image=pix,
                                    text=_('As is'),
                                    command=self._setButtonPressed,
                                    state='disabled',
                                    bd=config.border_width)
            Store.app.balloon.bind(self.setButton,
                                   _('Leave text as is - do not interpret'))
            self.setButton.pack(side='left')
        else:
            self.setButton = None

        pix = Store.app.request('pixmap', name='subnum')
        self.numbersToSubButton = Button(
            self,
            image=pix,
            text=_('Sub numbers'),
            command=self._numbersToSubButtonPressed,
            state='disabled',
            bd=config.border_width)
        Store.app.balloon.bind(self.numbersToSubButton,
                               _('Convert numbers to subscript'))
        self.numbersToSubButton.pack(side='left')

        # text decoration
        decorFrame = Frame(self)
        decorFrame.pack(padx=5, side="left")
        for i in self.font_decorations:
            pix = Store.app.request('pixmap', name=i)
            self.__dict__[i] = Button(
                self,
                image=pix,
                command=misc.lazy_apply(self._tag_it,
                                        (self.font_decorations_to_html[i], )),
                state='disabled',
                text=self.font_decorations_to_names[i],
                bd=config.border_width)
            Store.app.balloon.bind(self.__dict__[i],
                                   self.font_decorations_to_names[i])
            self.__dict__[i].pack(side="left")

        # special characters
        pix = Store.app.request('pixmap', name='specialchar')
        self.specialCharButton = Button(self,
                                        image=pix,
                                        text=_('Special Character'),
                                        command=self._specialCharButtonPressed,
                                        state='disabled',
                                        bd=config.border_width)
        Store.app.balloon.bind(self.specialCharButton,
                               _('Insert a special character'))
        self.specialCharButton.pack(side='left')
        self.active = False

    def _interpretButtonPressed(self, *e):
        t = self.editPool.get()
        if string.lower(t) in groups_table:
            self._setText(t)
            #self._setText( groups_table[ string.lower(t)]['text'])
            #self.editPool.insert(0, self.text)
        else:
            self._setText(t)
            self.text = re.sub("\\\\n", "\n", self.text)
        self._quit()

    def _setButtonPressed(self, *e):
        self._setText(self.editPool.get())
        self.interpret = 0
        self._quit()

    def _numbersToSubButtonPressed(self, *e):
        self._setText(re.sub("\d+", '<sub>\g<0></sub>', self.editPool.get()))
        self._quit()

    def _cancel(self, e):
        self._setText(None)
        self.active = False
        self._quit()

    def _quit(self):
        self.grab_release()
        self._disable()
        self._normaly_terminated = 1
        self.active = False
        self.quit()

    def _disable(self):
        self.interpretButton.configure(state='disabled')
        self.numbersToSubButton.configure(state='disabled')
        self.setButton.configure(state='disabled')
        self.editPool.configure(state='disabled')
        self.italic.configure(state='disabled')
        self.bold.configure(state='disabled')
        self.superscript.configure(state='disabled')
        self.subscript.configure(state='disabled')
        self.specialCharButton.configure(state='disabled')

    def _enable(self):
        self.interpretButton.configure(state='normal')
        self.numbersToSubButton.configure(state='normal')
        self.setButton.configure(state='normal')
        self.editPool.configure(state='normal')
        self.italic.configure(state='normal')
        self.bold.configure(state='normal')
        self.superscript.configure(state='normal')
        self.subscript.configure(state='normal')
        self.specialCharButton.configure(state='normal')

    def _setText(self, text):
        self.text = text
        self._update()

    def _update(self):
        self.editPool.delete(0, last='end')
        if self.text:
            self.editPool.insert(0, self.text)

    def activate(self, text=None, select=1):
        """activates edit_pool and returns inserted value (None if cancel occured),
    if parameter text is None it preserves the old one, use text='' to delete old text"""
        self.active = True
        self.interpret = 1
        self.focus_set()
        self.grab_set()
        self._enable()
        # this is because I need to distinguish whether the mainloop was terminated "from inside"
        # or from outside (this most of the time means the application was killed and the widgets are no longer available)
        self._normaly_terminated = 0
        if text != None:
            self._setText(text)
        self.editPool.focus_set()
        if select:
            self.editPool.selection_range(0, 'end')
        self.mainloop()
        if self._normaly_terminated:
            return self.text
        else:
            return None

    def _tag_it(self, tag):
        if self.editPool.selection_present():
            self.editPool.insert(Tkinter.SEL_FIRST, '<%s>' % tag)
            self.editPool.insert(Tkinter.SEL_LAST, '</%s>' % tag)
        else:
            self.editPool.insert(Tkinter.INSERT, '<%s></%s>' % (tag, tag))
            self.editPool.icursor(
                self.editPool.index(Tkinter.INSERT) - len(tag) - 3)

    def _key(self, event):
        if len(event.keysym) > 1 and event.keysym in keysyms:
            if self.editPool.selection_present():
                self.editPool.delete("anchor", "insert")
            self.editPool.insert('insert', unicode(keysyms[event.keysym]))
            return "break"

    def _specialCharButtonPressed(self):
        dialog = special_character_menu(self._insertText)
        dialog.post(self.specialCharButton.winfo_rootx(),
                    self.specialCharButton.winfo_rooty())

    def _insertText(self, text):
        if text != None:
            self.editPool.insert(Tkinter.INSERT, text)
        self.grab_set()
Example #21
0
class Main(Frame):
    """
    Main class of the system.
    """

    def __init__(self, master=None):
        """
        Main contstructor. Creates an instance of :class:`Storage<storage.Storage>` and starts the graphics-window.
        """
        args = {
            "fields": ["name", "date", "lifetime"],
            "ident": "name",
            "uniqueident": True,
            "objectname": "person",
            "gui": self,
        }
        self.storage = Storage(**args)
        self.is_clicked = False
        self.clicked_id = -1
        Frame.__init__(self, master)
        self.master.title("Medlemsregister Cybernetisk Selskab")
        self.grid(padx=15, pady=15)

        if not self.storage._testfile():
            path = os.path.abspath(__file__).rsplit("/", 1)[0]
            self._popup(
                "ERROR!",
                'Cannot write to file! make sure folder "{}/medlemslister" exists, then restart..'.format(path),
                "error",
            )
            self.destroy()
            self.master.destroy()
            return

        self.create_elements()

        loadmsg = self.storage.load()
        if "error" in loadmsg:
            self.infotext.set("ERROR! {}".format(loadmsg["error"]))
        elif "success" in loadmsg:
            self.infotext.set("Success! {}".format(loadmsg["success"]))

        self._populate_list()

    def create_elements(self):
        """
        creates all graphics elements and places them in the graphics grid.
        """

        # global shortcuts
        self.master.bind("<F1>", self.display_help)
        self.master.bind("<Control-f>", self.search)
        self.master.bind("<Control-d>", self.delete)
        self.master.bind("<Control-r>", self._populate_list)
        self.master.bind("<Control-s>", self.save_to_file)

        monospace = tkFont.Font(family="Courier", size=10, weight="normal")

        # menubar:
        menubar = Menu(self.master)

        backupmenu = Menu(menubar, tearoff=0)
        backupmenu.add_command(label="Backup to Google (Note: Slow!)", command=self.google_write)
        backupmenu.add_command(label="Read backup from Google", command=self.google_read)
        backupmenu.add_separator()
        backupmenu.add_command(label="Merge with Wiki", command=self.wiki_merge)
        backupmenu.add_command(label="Overwrite Wiki with local storage", command=self.wiki_overwrite)

        specialmenu = Menu(menubar, tearoff=0)
        specialmenu.add_command(label="Set as lifetime member", command=self.set_lifetime)
        specialmenu.add_command(label="Remove lifetime membership", command=self.unset_lifetime)
        specialmenu.add_command(label="Change a users id", command=self.update_id)

        menubar.add_cascade(label="Backup", menu=backupmenu)
        menubar.add_cascade(label="Special Actions", menu=specialmenu)
        menubar.add_command(label="Help (F1)", command=self.display_help)

        self.master.config(menu=menubar)

        # Info-label
        self.infotext = StringVar()
        self.info = Label(self, textvariable=self.infotext)
        self.info.pack()
        self.info.grid(row=0, column=0, columnspan=10)
        self.infotext.set("Welcome")

        # Save-button
        self.savebtn = Button(self, text="Save (enter)", command=self.create, width=11)
        self.savebtn.grid(row=3, column=7)

        # Omnibar (entry-field for add/search/delete)
        self.omnibar = Entry(self, width=28)
        self.omnibar.grid(row=3, column=0, columnspan=1)
        self.omnibar.bind("<Return>", self.create)
        self.omnibar.configure(font=monospace)

        # List of members
        self.memlist = SL(self, height=25, width=71, callback=self._click_list)
        self.memlist.grid(row=7, column=0, columnspan=10)
        self.memlist.listbox.configure(font=monospace)

        # Search-button
        self.searchbtn = Button(self, text="Search (ctrl-f)", command=self.search, width=11)
        self.searchbtn.grid(row=3, column=8)

        self.searchlist = False

        # Delete-button
        self.delete_btn = Button(self, text="Delete (ctrl-d)", command=self.delete, width=11)
        self.delete_btn.grid(row=3, column=9)

        # Counter
        self.count = StringVar()
        self.countlbl = Label(self, textvariable=self.count)
        self.countlbl.pack()
        self.countlbl.grid(row=8, column=0, sticky="W")

        # Reset list-button
        self.refreshbtn = Button(self, text="Refresh list (ctrl-r)", command=self._populate_list, width=12)
        self.refreshbtn.grid(row=8, column=9)

        # Save to file-button
        self.saveallbtn = Button(self, text="Save to file (ctrl-s)", command=self.save_to_file, width=12)
        self.saveallbtn.grid(row=8, column=8)

        # Help-button
        # self.helpbutton=Button(self, text='Help', command=self.display_help, width=11)
        # self.helpbutton.grid(row=8, column=7)

    def display_help(self, event=None):
        """
        Display a new window with help-text from file 'help.txt'
        """
        help = Toplevel()
        help.title("Help and usage")
        path = os.path.abspath(__file__).rsplit("/", 1)[0]
        f = open(u"{}/help.txt".format(path), "r")
        helptext = f.read()
        f.close
        helplabel = Label(help, text=helptext, relief=RIDGE, padx=15, pady=15, anchor="w", justify=LEFT, bg="white")
        helplabel.pack(side=TOP, fill=BOTH, expand=YES)

    def create(self, event=None):
        """
        Called when a user clicks the 'save person'-button or presses enter while typing in the name-field.
        Sets the info-label with feedback from :class:`Storage<storage.Storage>`

        :param event: the button-event of the enter-key.
        """
        if self.searchlist:
            self._populate_list()
            self.searchlist = False

        name = self._get_val()
        date = dt.now().strftime("%Y-%m-%d %H:%M")

        obj = self.storage.create(**{"name": name, "date": date, "lifetime": "n"})
        if not "success" in obj:
            self.infotext.set(u"FAILURE! {}".format(obj["error"]))
        else:
            self.infotext.set(u"Success! User added with id: {}".format(obj["success"]))
            self._list_add(obj["success"], obj["object"]["name"], obj["object"]["date"])

        self._update_count()

    def search(self, event=None):
        """
        Locate all people matching search-parameters in search-fields.

        called when user clicks search or when user presses enter while cursor is in one of the search-fields.

        :param event: button-event for enter-click.
        """
        self.infotext.set("")
        text = self._get_val()

        name = ""
        date = ""

        if len(text.split("-")) > 1 or len(text.split(":")) == 2:
            date = text
        else:
            name = text

        args = {"name": name, "date": date}

        obj = self.storage.search(**args)
        self.searchlist = True
        self.memlist.clear()
        i = 0
        l = 0
        for k, v in obj.iteritems():
            self._list_add(k, v["name"], v["date"])
            if not "L" in "{}".format(k):
                i += 1
            else:
                l += 1

        self._update_count(u"Life: {} Normal: {}".format(l, i))

    def delete(self, event=None):
        """
        Delete a person from collection based on `id`.

        called when user clicks delete or when user presses enter while cursor is in the delete-field.
        """
        val = self._get_val()

        if val == "":
            if self.is_clicked:
                id = self.clicked_id
                self.is_clicked = False
                self.clicked_id = -1
            else:
                self.infotext.set(u"FAILURE! No id provided. Either click a person in the list or write an id.")
                return
        elif "L" in val:
            id = val
        else:
            id = int(val)

        obj = self.storage.read(**{"id": id})
        if "success" in obj:
            check = self._popup(
                u"Really delete?",
                u"Do you really want to delete '{}'?".format(obj["success"]["name"].title()),
                "warning",
            )
            if not check:
                self.infotext.set(u"Delete aborted..")
                return

        obj = self.storage.delete(**{"id": id})
        if "success" in obj:
            self.infotext.set(u"Success! {}".format(obj["success"]))
            self._populate_list()
        else:
            self.infotext.set(u"FAILURE! {}".format(obj["error"]))
        self._update_count()

    def _list_add(self, id, name, date):
        """
        adds a person with id, name and timestamp to the list of users in the ui.

        :param id: id of a person.
        :param name: name of a person.
        :param date: date of a person.
        """
        self.memlist.append(u" {:<5} - {:40} - {}".format(id, name.title(), date))

    def _populate_list(self, event=None):
        """
        Refreshes the list of users in the ui.
        """
        self.memlist.clear()
        sorted_keys = sorted(self.storage.storage.iterkeys())
        for k in sorted_keys:
            v = self.storage.storage[k]
            self._list_add(k, v["name"], v["date"])
        self._update_count()

    def _update_count(self, count=None):
        """
        Updates the counter in the ui with number from :func:`storage.size()<storage.Storage.size>`
        """
        if count:
            self.count.set(u"{}".format(count))
        else:
            self.count.set(u"Total: {}".format(self.storage.size()))

    def _click_list(self, linenum):
        """
        called when a user clicks a member in the list of members. Saves the id of the user.

        :param linenum: the linenumber the user clicked.
        """
        line = ""
        try:
            line = self.memlist[linenum]
        except (IndexError):
            return
        self._get_val()
        vals = line.split("-")
        if not "L" in vals[0]:
            self.clicked_id = int(vals[0].strip())
        else:
            self.clicked_id = vals[0].strip()
        self.is_clicked = True

    def google_write(self):
        """
        backup collection to a google spreadsheet
        """
        obj = self.storage.google_write()
        if "success" in obj:
            self.infotext.set(u"Success! collection backed up to google spreadsheet.")
        else:
            self.infotext.set(u"Failure! {}".format(obj["error"]))

    def google_read(self):
        """
        read backup of collection from a google spreadsheet
        """
        obj = self.storage.google_read()
        if "success" in obj:
            self.infotext.set(u"Success! {}".format(obj["success"]))
            self._populate_list()
        else:
            self.infotext.set(u"Failure! {}".format(obj["error"]))

    def wiki_merge(self):
        """
        Merge local collection with wiki
        """
        self.infotext.set(u"Please Wait...")
        val = self.storage.wiki_merge()
        val = self.storage.wiki_merge(lifetime=True)
        self.infotext.set(val["status"])

    def wiki_overwrite(self):
        """
        overwrite wiki with data from local storage
        """
        self.infotext.set(u"Please Wait...")
        val = self.storage.wiki_merge(overwrite_wiki=True, push_to_wiki=True)
        val = self.storage.wiki_merge(overwrite_wiki=True, push_to_wiki=True, lifetime=True)
        self.infotext.set(val["status"])

    def set_lifetime(self):
        """
        register lifetime membership for a user. The user is selected by clicking in the list.
        """
        if not self.is_clicked:
            self.infotext.set(u"FAILURE! No id provided. You have to click a person in the list!.")
            return

        id = self.clicked_id
        self.is_clicked = False
        self.clicked_id = -1

        obj = self.storage.read(**{"id": id})
        if "success" in obj:
            check = self._popup(
                u"Set lifetime membership?",
                u"Do you really want to give '{}' a lifetime membership?".format(obj["success"]["name"].title()),
                "warning",
            )
            if not check:
                self.infotext.set(u"{} does NOT have a lifetime membership..".format(obj["success"]["name"].title()))
                return

        obj = self.storage.update(**{"id": id, "life": True})
        if "error" in obj:
            self.infotext.set(u"FAILURE! {}".format(obj["error"]))
        elif "success" in obj:
            self.infotext.set(u"Success! {}".format(obj["success"]))
            self._populate_list()

    def unset_lifetime(self):
        """
        remove a lifetime membership from a user. The user is selected by clicking in the list.
        """
        if not self.is_clicked:
            self.infotext.set(u"FAILURE! No id provided. You have to click a person in the list!.")
            return

        id = self.clicked_id
        self.is_clicked = False
        self.clicked_id = -1

        obj = self.storage.read(**{"id": id})
        if "success" in obj:
            check = self._popup(
                u"Remove lifetime membership?",
                u"Do you really want to remove '{}'s' lifetime membership?".format(obj["success"]["name"].title()),
                "warning",
            )
            if not check:
                self.infotext.set(u"{} is still a lifetime member.".format(obj["success"]["name"].title()))
                return

        obj = self.storage.update(**{"id": id, "life": False})
        if "error" in obj:
            self.infotext.set(u"FAILURE! {}".format(obj["error"]))
        elif "success" in obj:
            self.infotext.set(u"Success! {}".format(obj["success"]))
            self._populate_list()

    def update_id(self):
        """
        Update the id of a user
        """
        if not self.is_clicked:
            self.infotext.set(u"FAILURE: You have to click a user in the list.")
            return

        newid = self._get_val()
        if newid == "":
            self.infotext.set(u"FAILURE: You have to enter a new id in the textfield.")
            return

        id = self.clicked_id
        self.is_clicked = False
        self.clicked_id = -1

        name = self.storage.read(**{"id": id})
        if not "success" in name:
            self.infotext.set(u"FAILURE: id could not be found..")
            return

        name = u"{}".format(name["success"]["name"].title())
        if not self._popup(u"Change id?", u"Do you really want to change the id of '{}'?".format(name)):
            self.infotext.set(u"Aborted changing id.")
            return

        retval = self.storage.update_id(id, newid)

        self.infotext.set(retval["status"])

        self._populate_list()

    def _get_val(self):
        """
        clears the input-field and returns value that was there.
        """
        val = self.omnibar.get()
        self.omnibar.delete(0, END)
        val = u"{}".format(val)
        return val.lower()

    def save_to_file(self, event=None):
        val = self.storage.save()

        self.infotext.set("{}".format(val["msg"]))

    def _popup(self, title, text, style=None):
        """
        create a popup!

        :param title: title of the popup-window
        :param text: the text in the popup-window
        :param style: the icon-style of the popup. default is 'warning'
        """
        if style:
            if style == "error":
                return tkMessageBox.showerror(title, text)
            return tkMessageBox.askokcancel(title, text, icon=style)
        return tkMessageBox.askokcancel(title, text)
Example #22
0
class CHEOBCMAKiosk:
    def __init__(self, top=None):
        ' "It is a good habit, when building any type of GUI component, to keep a reference to our parent" '
        self.top = top
        top.geometry("600x450+525+240")
        top.title("CHEO BCMA KIOSK")
        top.configure(background="#d9d9d9")
        top.configure(highlightbackground="#d9d9d9")
        top.configure(highlightcolor="black")
        '''------------------------------------------------------------------------------------------------------
        Begin Build Text Box '''
        self.TextBox = Text(top)
        self.TextBox.place(relx=0.2, rely=0.15, relheight=0.34, relwidth=0.64)
        self.TextBox.configure(background="white")
        self.TextBox.configure(borderwidth="2")
        self.TextBox.configure(highlightbackground="#d9d9d9")
        self.TextBox.configure(highlightcolor="black")
        self.TextBox.configure(relief=RIDGE)
        self.TextBox.configure(takefocus="no")
        ' Bind mouse clicks '
        self.TextBox.bind("<Button-1>", self.textbox_text)
        self.TextBox.bind("<Button-2>", self.textbox_text)
        self.TextBox.bind("<Button-3>", self.textbox_text)
        ' Initial value '
        self.TextBox.insert(END, "This is the initial text.")
        ' Disable content from user entry '
        self.TextBox.config(state=DISABLED)

        self.LabelTitle = Label(top)
        self.LabelTitle.place(relx=0.03, rely=0.03, height=19, width=311)
        self.LabelTitle.configure(activebackground="#f9f9f9")
        self.LabelTitle.configure(activeforeground="black")
        self.LabelTitle.configure(background="#d9d9d9")
        self.LabelTitle.configure(disabledforeground="#a3a3a3")
        self.LabelTitle.configure(foreground="#000000")
        self.LabelTitle.configure(highlightbackground="#d9d9d9")
        self.LabelTitle.configure(highlightcolor="black")
        self.LabelTitle.configure(
            text=
            '''Welcome to the CHEO self-serve BCMA employee barcode kiosk''')
        ''' End Build Canvas
        ------------------------------------------------------------------------------------------------------'''
        ''' Build Buttons
        ------------------------------------------------------------------------------------------------------'''
        # Print Button
        self.ButtonPrint = Button(top)
        self.ButtonPrint.configure(command=self.printBut)
        self.ButtonPrint.place(relx=0.42, rely=0.89, height=21, width=31)
        self.ButtonPrint.configure(text='''Print''')
        self.ButtonPrint.configure(underline="0")
        self.ButtonPrint.configure(default='active')
        self.ButtonPrint.configure(takefocus='Yes')
        # Close Button
        self.ButtonClose = Button(top)
        self.ButtonClose.configure(command=quit)
        self.ButtonClose.place(relx=0.55, rely=0.89, height=21, width=35)
        self.ButtonClose.configure(activebackground="#d9d9d9")
        self.ButtonClose.configure(activeforeground="#000000")
        self.ButtonClose.configure(background="#d9d9d9")
        self.ButtonClose.configure(disabledforeground="#a3a3a3")
        self.ButtonClose.configure(foreground="#000000")
        self.ButtonClose.configure(highlightbackground="#d9d9d9")
        self.ButtonClose.configure(highlightcolor="black")
        self.ButtonClose.configure(pady="0")
        self.ButtonClose.configure(text='''Close''')
        self.ButtonClose.configure(underline="0")
        ''' End Build Buttons
        ------------------------------------------------------------------------------------------------------'''
        ''' Begin Build Radio Group
        ------------------------------------------------------------------------------------------------------'''
        # Default Radio Button Source to TAP
        self.input_source = StringVar()
        self.input_source.set('TAP')

        # Tap Data Entry Radio
        self.rdo_TAP = Radiobutton(top)
        self.rdo_TAP.place(relx=0.8, rely=0.82, relheight=0.05, relwidth=0.14)
        self.rdo_TAP.configure(activebackground="#d9d9d9")
        self.rdo_TAP.configure(activeforeground="#000000")
        self.rdo_TAP.configure(background="#d9d9d9")
        self.rdo_TAP.configure(disabledforeground="#a3a3a3")
        self.rdo_TAP.configure(foreground="#000000")
        self.rdo_TAP.configure(highlightbackground="#d9d9d9")
        self.rdo_TAP.configure(highlightcolor="black")
        self.rdo_TAP.configure(justify=LEFT)
        self.rdo_TAP.configure(text='Tap Reader')
        self.rdo_TAP.configure(underline="0")
        self.rdo_TAP.configure(value='TAP')
        self.rdo_TAP.configure(variable=self.input_source)
        self.rdo_TAP.configure(command=self.radio_toggle)
        # Manual Data Entry Radio
        self.rdo_MAN = Radiobutton(top)
        self.rdo_MAN.place(relx=0.8, rely=0.89, relheight=0.05, relwidth=0.15)
        self.rdo_MAN.configure(activebackground="#d9d9d9")
        self.rdo_MAN.configure(activeforeground="#000000")
        self.rdo_MAN.configure(background="#d9d9d9")
        self.rdo_MAN.configure(disabledforeground="#a3a3a3")
        self.rdo_MAN.configure(foreground="#000000")
        self.rdo_MAN.configure(highlightbackground="#d9d9d9")
        self.rdo_MAN.configure(highlightcolor="black")
        self.rdo_MAN.configure(justify=LEFT)
        self.rdo_MAN.configure(text='Manual Entry')
        self.rdo_MAN.configure(underline="0")
        self.rdo_MAN.configure(value="MAN")
        self.rdo_MAN.configure(variable=self.input_source)
        self.rdo_MAN.configure(command=self.radio_toggle)
        ''' End Build Radio Group
        ------------------------------------------------------------------------------------------------------'''
        ''' Begin Fixed Labels
        ------------------------------------------------------------------------------------------------------'''
        # Last Name
        self.LabelLastName = Label(top)
        self.LabelLastName.place(relx=0.1, rely=0.56, height=19, width=56)
        self.LabelLastName.configure(activebackground="#f9f9f9")
        self.LabelLastName.configure(activeforeground="black")
        self.LabelLastName.configure(background="#d9d9d9")
        self.LabelLastName.configure(disabledforeground="#a3a3a3")
        self.LabelLastName.configure(foreground="#000000")
        self.LabelLastName.configure(highlightbackground="#d9d9d9")
        self.LabelLastName.configure(highlightcolor="black")
        self.LabelLastName.configure(text='''Last Name''')
        # First Name
        self.LabelFirstName = Label(top)
        self.LabelFirstName.place(relx=0.1, rely=0.62, height=19, width=57)
        self.LabelFirstName.configure(activebackground="#f9f9f9")
        self.LabelFirstName.configure(activeforeground="black")
        self.LabelFirstName.configure(background="#d9d9d9")
        self.LabelFirstName.configure(disabledforeground="#a3a3a3")
        self.LabelFirstName.configure(foreground="#000000")
        self.LabelFirstName.configure(highlightbackground="#d9d9d9")
        self.LabelFirstName.configure(highlightcolor="black")
        self.LabelFirstName.configure(text='''First Name''')
        # AD User Name
        self.LabelADUserName = Label(top)
        self.LabelADUserName.place(relx=0.07, rely=0.69, height=19, width=75)
        self.LabelADUserName.configure(activebackground="#f9f9f9")
        self.LabelADUserName.configure(activeforeground="black")
        self.LabelADUserName.configure(background="#d9d9d9")
        self.LabelADUserName.configure(disabledforeground="#a3a3a3")
        self.LabelADUserName.configure(foreground="#000000")
        self.LabelADUserName.configure(highlightbackground="#d9d9d9")
        self.LabelADUserName.configure(highlightcolor="black")
        self.LabelADUserName.configure(text='''AD User Name''')
        # AD Password
        self.LabelADPassword = Label(top)
        self.LabelADPassword.place(relx=0.08, rely=0.76, height=19, width=70)
        self.LabelADPassword.configure(activebackground="#f9f9f9")
        self.LabelADPassword.configure(activeforeground="black")
        self.LabelADPassword.configure(background="#d9d9d9")
        self.LabelADPassword.configure(disabledforeground="#a3a3a3")
        self.LabelADPassword.configure(foreground="#000000")
        self.LabelADPassword.configure(highlightbackground="#d9d9d9")
        self.LabelADPassword.configure(highlightcolor="black")
        self.LabelADPassword.configure(text='''AD Password''')
        ''' End Fixed Labels
        ------------------------------------------------------------------------------------------------------'''
        ''' Begin Data Entry
        ------------------------------------------------------------------------------------------------------'''
        # Last Name
        self.EntryLastName = Entry(top)
        self.EntryLastName.place(relx=0.2,
                                 rely=0.56,
                                 relheight=0.04,
                                 relwidth=0.34)
        self.EntryLastName.configure(background="white")
        self.EntryLastName.configure(disabledforeground="#a3a3a3")
        self.EntryLastName.configure(font="TkFixedFont")
        self.EntryLastName.configure(foreground="#000000")
        self.EntryLastName.configure(highlightbackground="#d9d9d9")
        self.EntryLastName.configure(highlightcolor="black")
        self.EntryLastName.configure(insertbackground="black")
        self.EntryLastName.configure(selectbackground="#c4c4c4")
        self.EntryLastName.configure(selectforeground="black")
        ' Bind mouse clicks '
        self.EntryLastName.bind("<Button-1>", self.lastname_text)
        self.EntryLastName.bind("<Button-2>", self.lastname_text)
        self.EntryLastName.bind("<Button-3>", self.lastname_text)
        'self.EntryLastName.configure(state=readonly)'
        ' First Name '
        self.EntryFirstName = Entry(top)
        self.EntryFirstName.place(relx=0.2,
                                  rely=0.62,
                                  relheight=0.04,
                                  relwidth=0.34)
        self.EntryFirstName.configure(background="white")
        self.EntryFirstName.configure(disabledforeground="#a3a3a3")
        self.EntryFirstName.configure(font="TkFixedFont")
        self.EntryFirstName.configure(foreground="#000000")
        self.EntryFirstName.configure(highlightbackground="#d9d9d9")
        self.EntryFirstName.configure(highlightcolor="black")
        self.EntryFirstName.configure(insertbackground="black")
        self.EntryFirstName.configure(selectbackground="#c4c4c4")
        self.EntryFirstName.configure(selectforeground="black")
        '''self.EntryFirstName.configure(label="Hi There")
        readonly = 'readonly'
        self.EntryFirstName.configure(state=readonly)'''
        ' AD User Name '
        self.EntryADUserName = Entry(top)
        self.EntryADUserName.place(relx=0.2,
                                   rely=0.69,
                                   relheight=0.04,
                                   relwidth=0.34)
        self.EntryADUserName.configure(background="white")
        self.EntryADUserName.configure(disabledforeground="#a3a3a3")
        self.EntryADUserName.configure(font="TkFixedFont")
        self.EntryADUserName.configure(foreground="#000000")
        self.EntryADUserName.configure(highlightbackground="#d9d9d9")
        self.EntryADUserName.configure(highlightcolor="black")
        self.EntryADUserName.configure(insertbackground="black")
        self.EntryADUserName.configure(selectbackground="#c4c4c4")
        self.EntryADUserName.configure(selectforeground="black")
        readonly = 'readonly'
        self.EntryADUserName.configure(state=readonly)
        ' Data Payload '
        self.EntryADPassword = Entry(top)
        self.EntryADPassword.place(relx=0.2,
                                   rely=0.76,
                                   relheight=0.04,
                                   relwidth=0.34)
        self.EntryADPassword.configure(background="white")
        self.EntryADPassword.configure(disabledforeground="#a3a3a3")
        self.EntryADPassword.configure(font="TkFixedFont")
        self.EntryADPassword.configure(foreground="#000000")
        self.EntryADPassword.configure(highlightbackground="#d9d9d9")
        self.EntryADPassword.configure(highlightcolor="black")
        self.EntryADPassword.configure(insertbackground="black")
        self.EntryADPassword.configure(selectbackground="#c4c4c4")
        self.EntryADPassword.configure(selectforeground="black")
        '''readonly = 'readonly'
        self.EntryADPassword.configure(state=readonly)'''
        ''' End Data Entry Fields
        ------------------------------------------------------------------------------------------------------'''
        ''' Begin Status Bar
        ------------------------------------------------------------------------------------------------------'''
        # Create a sunken status bar in the root object with a border
        self.status_text = StringVar()  # Displays live status
        self.status_text.set("Hello")
        self.status = Label(root,
                            textvariable=self.status_text,
                            bd=1,
                            relief=SUNKEN,
                            anchor=W)  # anchor to the West (Left)
        self.status.pack(side=BOTTOM, fill=X)  # display
        ''' End Status Bar
        ------------------------------------------------------------------------------------------------------'''

    ' Print Button Function'

    def printBut(self):
        ' Instantiate ZPLII Class '
        ' ??? @@@ '
        print('Print button has been pressed')
        print('Current values... ' + str(self.EntryFirstName))
        self.status = "Q"
        # self.input_source.set(_self.input_source.Get)

    def radio_toggle(self):
        ' @@@ '
        selection = self.input_source.get()
        print('Radio button is ' + selection)
        self.status_text.set("Radio toggled to " + selection)

    def textbox_text(self, event):
        print('Text Box Event - ' + str(event))
        ' Enable before insert '
        if self.TextBox["state"] == DISABLED:
            self.TextBox.config(state=NORMAL)
        self.TextBox.insert(END, "\nMouse click in TextBox")
        ' Disable after insert '
        self.TextBox.config(state=DISABLED)

    def lastname_text(self, event):
        print('LastName Entry Event - ' + str(event))
        ' Enable before insert '
        if self.TextBox["state"] == DISABLED:
            self.TextBox.config(state=NORMAL)
        self.TextBox.insert(END, "\nMouse click in Last Name field")
        ' Disable after insert '
        self.TextBox.config(state=DISABLED)
        ' Update status depending on which button pressed '
        if event.num == 1:
            self.status_text.set("Left button clicked")
        elif event.num == 2:
            self.status_text.set("Middle button clicked")
        elif event.num == 3:
            self.status_text.set("Right button clicked")
        else:
            self.status_text.set("*** The " + str(event.num) +
                                 " button pressed ***")
Example #23
0
class App:
    def __init__(self, master):
        self.master = master
        column0_padx = 24
        row_pady = 40
        self.imgck = IntVar()
        self.latck = IntVar()
        self.lonck = IntVar()
        self.timeck = IntVar()
        self.dateck = IntVar()
        self.datestate = int()
        self.imgval = StringVar()
        self.latval = StringVar()
        self.lonval = StringVar()
        self.timeval = StringVar()
        self.dateval = StringVar()
        self.headerVal = IntVar()
        self.rbv = IntVar()
        vcmd = (master.register(self.validate), '%d', '%i', '%P', '%s', '%S',
                '%v', '%V', '%W')

        self.entryExif = Entry(master, relief="sunken")
        self.entryExif.insert(0, "EXIF csv file")
        self.entryExif.grid(row=0, columnspan=4, sticky='EW', padx=5, pady=10)
        exifbtn = Button(master,
                         text="OPEN CSV file",
                         command=self.getEXIFfile)
        exifbtn.grid(row=1, column=0, padx=5, sticky='w')

        ##added to allow header line
        self.headerOpt = Checkbutton(master,
                                     text="Select if CSV file has header line",
                                     variable=self.headerVal)
        self.headerOpt.grid(row=2, column=0, padx=5, sticky='w')

        self.entryJPGS = Entry(master, relief="sunken")
        self.entryJPGS.insert(0, "JPEG folder")
        self.entryJPGS.grid(row=3, columnspan=4, sticky='EW', padx=5, pady=10)
        JPGbtn = Button(master,
                        text="OPEN JPEG folder",
                        command=self.getJPEGFolder)
        JPGbtn.grid(row=4, column=0, padx=5, sticky='w')

        self.paramFile = Entry(master, relief="sunken")
        self.paramFile.insert(0, "Param file")
        self.paramFile.grid(row=5, columnspan=4, sticky='EW', padx=5, pady=10)
        parambtn = Button(master,
                          text="OPEN PARAM file",
                          command=self.getParamfile)
        parambtn.grid(row=6, column=0, padx=5, sticky='w')

        lbl_exiftag = Label(master,
                            text="EXIF tag",
                            wraplength=100,
                            anchor='w',
                            justify='left')
        lbl_column = Label(master,
                           text="CSV column (zero based)",
                           wraplength=100,
                           anchor='w',
                           justify='left')
        cbImage = Checkbutton(master,
                              text='Image name',
                              variable=self.imgck,
                              command=self.imgcheck)
        cbLatitude = Checkbutton(master,
                                 text='Latitude',
                                 variable=self.latck,
                                 command=self.latcheck)
        cbLongitude = Checkbutton(master,
                                  text='Longitude',
                                  variable=self.lonck,
                                  command=self.loncheck)
        cbTime = Checkbutton(master,
                             text='GPSTime',
                             variable=self.timeck,
                             command=self.timecheck)
        cbDate = Checkbutton(master,
                             text='GPSDate',
                             variable=self.dateck,
                             command=self.datecheck)
        lblText = Label(master, text="Free text fields:")
        lblArtist = Label(master, text="Artist:")

        ##        lbl_analysis = Label(master, text="Analysis Library")
        self.entryImage = Entry(master,
                                validate='key',
                                validatecommand=vcmd,
                                width=5,
                                state='disabled')
        self.entryLat = Entry(master,
                              validate='key',
                              validatecommand=vcmd,
                              width=5,
                              state='disabled')
        self.entryLon = Entry(master,
                              validate='key',
                              validatecommand=vcmd,
                              width=5,
                              state='disabled')
        self.entryTime = Entry(master,
                               validate='key',
                               validatecommand=vcmd,
                               width=5,
                               state='disabled')
        self.entryDate = Entry(master,
                               validate='key',
                               validatecommand=vcmd,
                               width=5,
                               state='disabled')
        self.entryArtist = Entry(master, width=40)

        #lbl_testcase_exec.grid(row=0, column=2, padx=20, pady=12, sticky='w')
        lbl_exiftag.grid(row=7, column=0, padx=20, pady=12, sticky='w')
        lbl_column.grid(row=7, column=1, padx=10, pady=12, sticky='w')
        cbImage.grid(row=8, column=0, padx=20, sticky='w')
        cbLatitude.grid(row=9, column=0, padx=20, sticky='w')
        cbLongitude.grid(row=10, column=0, padx=20, sticky='w')
        cbTime.grid(row=11, column=0, padx=20, sticky='w')
        cbDate.grid(row=12, column=0, padx=20, sticky='w')
        lblText.grid(row=13, column=0, padx=30, sticky='w')
        lblArtist.grid(row=14, column=0, padx=20, sticky='w')
        self.entryImage.grid(row=8, column=1, padx=10, sticky='w')
        self.entryLat.grid(row=9, column=1, padx=10, sticky='w')
        self.entryLon.grid(row=10, column=1, padx=10, sticky='w')
        self.entryTime.grid(row=11, column=1, padx=10, sticky='w')
        self.entryDate.grid(row=12, column=1, padx=10, sticky='w')
        lbl_datefmt = Label(master,
                            text="Select date format:",
                            wraplength=500,
                            anchor='w',
                            justify='left')
        lbl_datefmt.grid(row=12, column=1, padx=50, sticky='w')
        self.entryArtist.grid(row=14, column=1, padx=10, sticky='w')
        ##        ##added to allow header line
        ##        self.dateOpt1 = Checkbutton(master, text="YYYYMMDD", variable=self.headerVal)
        ##        self.dateOpt1.grid(row=10, column=1, padx=160, sticky='w')
        ##        self.dateOpt2 = Checkbutton(master, text="YYYY:MM:DD", variable=self.headerVal)
        ##        self.dateOpt2.grid(row=10, column=1, padx=260, sticky='w')
        ##        self.dateOpt3 = Checkbutton(master, text="MM/DD/YYYY", variable=self.headerVal)
        ##        self.dateOpt3.grid(row=10, column=1, padx=360, sticky='w')

        #try radio buttons
        Radiobutton(master,
                    text="YYYYMMDD",
                    variable=self.rbv,
                    value=1,
                    command=self.rdioInvoke).grid(row=10,
                                                  column=1,
                                                  padx=190,
                                                  sticky='w')
        Radiobutton(master,
                    text="YYYY:MM:DD",
                    variable=self.rbv,
                    value=2,
                    command=self.rdioInvoke).grid(row=11,
                                                  column=1,
                                                  padx=190,
                                                  sticky='w')
        Radiobutton(master,
                    text="MM/DD/YYYY",
                    variable=self.rbv,
                    value=3,
                    command=self.rdioInvoke).grid(row=12,
                                                  column=1,
                                                  padx=190,
                                                  sticky='w')
        Radiobutton(master,
                    text="MM/DD/YY",
                    variable=self.rbv,
                    value=4,
                    command=self.rdioInvoke).grid(row=13,
                                                  column=1,
                                                  padx=190,
                                                  sticky='w')

        # buttons
        bottom_frame = Frame(master)
        bottom_frame.grid(row=30, column=1, columnspan=3, sticky='w')

        #I had to add the self to the prefix, otherwise my rdioInvoke wouldn't work.
        #I'm guessing the self is sort of the global aspect.
        #temporarily commenting this out so I can just test reading the param file
        self.btn_start = Button(bottom_frame,
                                text="Submit",
                                width=7,
                                command=self.MergeExif)
        #self.btn_start = Button(bottom_frame, text = "Submit", width=7, command=self.readParamfile)
        self.btn_start.pack(side='left', pady=20)
        self.btn_start.config(state='disabled')
        ##        btn_commit = Button(bottom_frame, text="Commit", width=7)
        ##        btn_commit.pack(side='left', padx=80)
        btn_exit = Button(bottom_frame,
                          text="Exit",
                          width=7,
                          command=self.cbtnClick)
        btn_exit.pack(side='left', padx=10)

    def rdioInvoke(self):
        print "rdioInvoke"
        self.btn_start.configure(state='normal')

    def cbtnClick(self):
        print "close button event handler"
        self.master.destroy()

    def imgcheck(self):
        print "check"
        if self.imgck.get() == 0:
            self.entryImage.configure(state='disabled')
        else:
            self.entryImage.configure(state='normal')

    def latcheck(self):
        print "check"
        if self.latck.get() == 0:
            self.entryLat.configure(state='disabled')
        else:
            self.entryLat.configure(state='normal')

    def loncheck(self):
        print "check"
        if self.lonck.get() == 0:
            self.entryLon.configure(state='disabled')
        else:
            self.entryLon.configure(state='normal')

    def timecheck(self):
        print "check"
        if self.timeck.get() == 0:
            self.entryTime.configure(state='disabled')
        else:
            self.entryTime.configure(state='normal')

    def datecheck(self):
        print "check"
        if self.dateck.get() == 0:
            self.entryDate.configure(state='disabled')
        else:
            self.entryDate.configure(state='normal')
            #self.datestate == 1
    def validate(self, action, index, value_if_allowed, prior_value, text,
                 validation_type, trigger_type, widget_name):
        if text in '0123456789':
            return True
        else:
            return False

    def getEXIFfile(self):
        EXIFcsvfile = tkFileDialog.askopenfilename(title='Image EXIF CSV file')
        #need to fix the next line
        self.entryExif.delete(0, END)
        if len(EXIFcsvfile) > 0:
            self.entryExif.insert(0, EXIFcsvfile)

    def getJPEGFolder(self):
        #by not specifying an intial directory, it starts where the script is located.
        JPGfolder = tkFileDialog.askdirectory(title='Pick JPEG folder')
        #need to clear anything that's there
        self.entryJPGS.delete(0, END)
        if len(JPGfolder) > 0:
            #print "now read JPEG folder %s" % JPGfolder
            #for entry widget
            self.entryJPGS.insert(0, JPGfolder)

    def getParamfile(self):
        PARAMtxtfile = tkFileDialog.askopenfilename(title='Paramter text file')
        self.paramFile.delete(0, END)
        if len(PARAMtxtfile) > 0:
            self.paramFile.insert(0, PARAMtxtfile)

    def readParamfile(self):
        params = self.paramFile.get()
        inputparams = open(params, "r")
        allparams = inputparams.read()
        for cmd3 in allparams.splitlines():
            if "-comment" in cmd3:
                ##                print cmd3
                ##                print " "
                val3 = cmd3
        for cmd4 in allparams.splitlines():
            if "-sep" in cmd4:
                ##                print cmd4
                ##                print " "
                #return cmd4
                val4 = cmd4

        for cmd6 in allparams.splitlines():
            if "-Caption=" in cmd6:
                ##                print cmd6
                ##                print " "
                #return cmd6
                val6 = cmd6

        for cmd9 in allparams.splitlines():
            if "-Caption-Abstract" in cmd9:
                ##                print cmd9
                ##                print " "
                #return cmd9
                val9 = cmd9

        for cmd10 in allparams.splitlines():
            if "-ImageDescription=" in cmd10:
                ##                print cmd10
                ##                print " "
                #return cmd10
                val10 = cmd10
##        print "read params"
##        print "val3"
##        print val3
        return (val3, val4, val6, val9, val10)

        #self.MergeExif()

    def MergeExif(self):
        try:
            test = self.entryExif.get()
            print test

            ##            print "date format"
            ##            print str(self.rbv.get())
            inputfile = open(test, "r")
            #print "made it here 1"
            imgval = int(self.entryImage.get())
            #print self.entryImage.get()
            #print str(imgval)
            if self.latck.get() <> 0:
                latval = int(self.entryLat.get())
            #print "made it here 1a"
            if self.lonck.get() <> 0:
                lonval = int(self.entryLon.get())
            print "made it here 1b"
            if self.timeck.get() <> 0:
                timeval = int(self.entryTime.get())
            print "made it here 1c"
            if self.dateck.get() <> 0:
                dateval = int(self.entryDate.get())
                print "got date"
                print str(dateval)
            print "made it here 2"
            ##add this if statement to deal with header value
            if self.headerVal.get() == 1:
                print "have a header value"
                line = inputfile.readline()
            else:
                print "no header value"
            print "getting return"
            ##            retcmd3, retcmd4, retcmd6, retcmd9, retcmd10 = self.readParamfile()
            ##            print "just cmd3"
            ##            print retcmd3
            allreturns = self.readParamfile()
            print "allreturns"
            print allreturns
            ##            print "first return"
            ##            print allreturns[0]
            while 1:
                line = inputfile.readline()
                print "made it here 3"
                values = str.split(line, ",")
                ##                print line
                ##                print "imgval"
                ##                print imgval
                ##if extension is included in text file
                img = values[imgval].strip()
                ##if extension is NOT included in text file
                ##img = values[imgval].strip() + '.JPG'
                vlat = values[latval].strip()
                vlon = values[lonval].strip()
                ingpsdate = values[dateval].strip()
                ##                #section to read date formats
                if self.rbv.get() == 1:
                    vyr = str(ingpsdate)[0:4]
                    vmm = str(ingpsdate)[4:6]
                    vdd = str(ingpsdate)[6:8]
                    vgpsdate = vyr + ":" + vmm + ":" + vdd
                if self.rbv.get() == 2:
                    vgpsdate = ingpsdate
                if self.rbv.get() == 3:
                    vmm, vdd, vyr = ingpsdate.split("/")
                    if len(vmm) == 1:
                        vmm = "0" + vmm
                    if len(vdd) == 1:
                        vdd = "0" + vdd
                    vgpsdate = vyr + ":" + vmm + ":" + vdd
                if self.rbv.get() == 4:
                    vmm, vdd, vyr = ingpsdate.split("/")
                    if len(vmm) == 1:
                        vmm = "0" + vmm
                    if len(vdd) == 1:
                        vdd = "0" + vdd
                    if int(vyr) < 50:
                        vyr = "20" + vyr
                    else:
                        vyr = "19" + vyr
                    vgpsdate = vyr + ":" + vmm + ":" + vdd
##                if ingpsdate.find(':')==-1:
##                    vyr=str(ingpsdate)[0:4]
##                    vmm=str(ingpsdate)[4:6]
####                    print ingpsdate
####                    print "year"
####                    print vyr
####                    print "month"
####                    print vmm
##                    vdd=ingpsdate[6:8]
##                    vgpsdate=vyr+":"+vmm+":"+vdd
##                else:
##                    vgpsdate=ingpsdate
                print vgpsdate
                vgpstime = values[timeval].strip()
                imagefolder = self.entryJPGS.get()
                fullimg = os.path.join(imagefolder, img)
                fullimg = fullimg.replace('\\', '/')
                vartist = self.entryArtist.get()
                vartistquotes = '"' + vartist + '"'
                ##                print str(fullimg)
                ##                print str(vlat)
                ##                print str(vlon)
                ##                print str(vgpsdate)
                ##                print str(vgpstime)
                if (float(vlat)) > 0:
                    print "latref1"
                    vlatref = 'N'
                else:
                    print "latref2"
                    vlatref = 'S'
                if (float(vlon)) > 0:
                    vlonref = 'E'
                else:
                    vlonref = 'W'


##                print str(vlatref)
##                print str(vlonref)
                cmd = "exiftool -GPSDateStamp=" + vgpsdate + " -GPSTimeStamp="+vgpstime+" -GPSLatitude="+vlat+" -GPSLatitudeRef="+ vlatref+\
                      " -GPSLongitude="+vlon+" -GPSLongitudeRef="+vlonref+" "+ " -Artist=" +vartistquotes +" "+fullimg
                print cmd
                #print "made it past first os.system"
                subprocess.check_call(cmd, shell=True)
                print "executed"
                cmd2 = """exiftool -Credit="U.S. Geological Survey" -Contact="[email protected] " """ + fullimg
                subprocess.check_call(cmd2, shell=True)

                #jpeg comment
                print "in command 3 section"
                cmd3 = allreturns[0]
                cmd3new = cmd3 + " " + fullimg
                print cmd3new
                #print cmd3
                #cmd3 = """exiftool -comment="Photo from down-looking camera on the USGS SEABOSS deployed from the R/V Rafael during survey 2012-003-FA (http://woodshole.er.usgs.gov/operations/ia/public_ds_info.php?fa=2012-003-FA). Released as part of publication DOI:10.3133/ds937. " """+ fullimg
                subprocess.check_call(cmd3new, shell=True)
                #iptc info
                #cmd4 = """exiftool -sep ", " -keywords="Barnegat Bay, New Jersey, 2012-003-FA, SEABOSS, sea floor, USGS " """+ fullimg
                cmd4 = allreturns[1]
                cmd4new = cmd4 + " " + fullimg
                #subprocess.check_call(cmd4, shell=True)
                subprocess.check_call(cmd4new, shell=True)
                #cmd5 unused and skipped

                #xmp info
                #cmd6 = """exiftool -Caption="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg
                cmd6 = allreturns[2]
                cmd6new = cmd6 + " " + fullimg
                #subprocess.check_call(cmd6, shell=True)
                subprocess.check_call(cmd6new, shell=True)
                print "did caption"
                #EXIF info
                cmd7 = """exiftool -Copyright="Public Domain - please credit U.S. Geological Survey " """ + fullimg
                subprocess.check_call(cmd7, shell=True)
                print "did copyright"
                #iptc info
                cmd8 = """exiftool -CopyrightNotice="Public Domain - please credit U.S. Geological Survey " """ + fullimg
                subprocess.check_call(cmd8, shell=True)
                #iptc info
                #cmd9 = """exiftool -Caption-Abstract="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg
                cmd9 = allreturns[3]
                cmd9new = cmd9 + " " + fullimg
                #subprocess.check_call(cmd9, shell=True)
                subprocess.check_call(cmd9new, shell=True)
                #exif info - software such as Picasso use this as the caption
                #cmd10 = """exiftool -ImageDescription="Photograph of the sea floor in Barnegat Bay, New Jersey from survey 2012-003-FA " """+ fullimg
                cmd10 = allreturns[4]
                cmd10new = cmd10 + " " + fullimg
                #subprocess.check_call(cmd10, shell=True)
                subprocess.check_call(cmd10new, shell=True)
        except:
            print "booboo maybe?"
        inputfile.close()
        print "done"
Example #24
0
class Example(Frame):
    def __init__(self, parent):
        self.catFactors = {}
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        if hasattr(self, 'frame0'):
            self.frame0.destroy()
        self.initUIRoot()
        self.initUIFrame()

    def initUIRoot(self):
        self.parent.title("集总模型")
        self.pack(fill=BOTH, expand=1)

        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        self.frame0 = Frame(self, relief=RAISED)
        self.frame0.pack(fill=BOTH, expand=True)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label=u"新建催化剂", command=self.onNewCata)
        fileMenu.add_command(label=u"精确预测", command=self.onNewPre)
        fileMenu.add_command(label=u"趋势预测", command=self.onNewGraph)
        fileMenu.add_command(label=u"最优条件预测", command=self.onNewBest)
        helpMenu = Menu(menubar)
        helpMenu.add_command(label=u"关于", command=self.onHelp)

        mainPageMenu = Menu(menubar)
        mainPageMenu.add_command(label=u"主页", command=self.initUI)
        menubar.add_cascade(label="主页", menu=mainPageMenu)
        menubar.add_cascade(label="操作", menu=fileMenu)
        menubar.add_cascade(label="帮助", menu=helpMenu)

    def initUIFrame(self):
        self.frame0.columnconfigure(0, pad=5, weight=1)
        self.frame0.columnconfigure(1, pad=5, weight=1)
        self.frame0.columnconfigure(2, pad=5, weight=1)
        self.frame0.columnconfigure(3, pad=5, weight=1)
        self.frame0.columnconfigure(4, pad=5, weight=1)
        self.frame0.columnconfigure(5, pad=5, weight=1)
        self.frame0.rowconfigure(0, pad=37)
        self.frame0.rowconfigure(1, pad=7)
        self.frame0.rowconfigure(2, pad=7, weight=1)
        titleImg = ImageTk.PhotoImage(file="./imgs/title.png")
        catImg = ImageTk.PhotoImage(file="./imgs/cat.png")
        preImg = ImageTk.PhotoImage(file="./imgs/pre.png")
        chartImg = ImageTk.PhotoImage(file="./imgs/chart.png")
        bestImg = ImageTk.PhotoImage(file="./imgs/bestPoint.png")
        rareImg = ImageTk.PhotoImage(file="./imgs/rare.png")

        lbl = Label(self.frame0, image=titleImg)
        lbl.grid(row=0, column=1,columnspan=5,sticky=S+W)
        lbl.image = titleImg
        lbl = Label(self.frame0, image=rareImg)
        lbl.grid(row=3, column=1,columnspan=5,sticky=S)
        lbl.image = rareImg
        preButton = Button(self.frame0, command=self.onNewPre)
        preButton.config(image=preImg)
        preButton.image = preImg
        preButton.grid(row=1, column=2)
        cateButton = Button(self.frame0, command=self.onNewCata)
        cateButton.config(image=catImg)
        cateButton.image = catImg
        cateButton.grid(row=1, column=1)
        chartButton = Button(self.frame0, command=self.onNewGraph)
        chartButton.config(image=chartImg)
        chartButton.image = chartImg
        chartButton.grid(row=1, column=3)
        chartButton = Button(self.frame0, command=self.onNewBest)
        chartButton.config(image=bestImg)
        chartButton.image = bestImg
        chartButton.grid(row=1, column=4)

        lbl = Label(self.frame0, text="新建催化剂")
        lbl.grid(row=2, column=1, sticky=N)
        lbl = Label(self.frame0, text="精确预测")
        lbl.grid(row=2, column=2, sticky=N)
        lbl = Label(self.frame0, text="趋势预测")
        lbl.grid(row=2, column=3, sticky=N)
        lbl = Label(self.frame0, text="最优条件预测")
        lbl.grid(row=2, column=4, sticky=N)
    def bestUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=False)

        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(1, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.columnconfigure(10, pad=7)
        frame1.rowconfigure(5, weight=1)
        frame1.rowconfigure(5, pad=7)

        frame2.columnconfigure(11, pad=7, weight=1)
        frame2.rowconfigure(8, pad=7)

        lbl = Label(frame1, text="催化剂性质")
        lbl.grid(row=0, column=0, columnspan=8, rowspan=1, sticky=W, pady=4, padx=5)
        # K_Mat_Tree = ttk.Treeview(frame1)
        # K_Mat_Tree['show'] = 'headings'
        # K_Mat_Tree = self.makeMatrixUI(7, K_Mat_Tree, sourceDate.K_model)
        # K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=5, sticky=E + W + S + N, pady=4, padx=5)
        K_Mat_Tree = Text(frame1, height=18)
        self.makeMatrixUI(K_Mat_Tree, self.catObj)
        K_Mat_Tree.configure(state='normal')
        K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=6, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="优化方法:")
        lbl.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.optMethod)
        txt.configure(state='readonly')
        txt.grid(row=0, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="集总数:")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.n)
        txt.configure(state='readonly')
        txt.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="精确度:")
        lbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.tol)
        txt.configure(state='readonly')
        txt.grid(row=2, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        cateDetailButton = Button(frame1, text="查看催化剂详情")
        cateDetailButton.grid(row=3, column=8)
        # ________________________________________
        lbl = Label(frame2, text="待预测条件")
        lbl.grid(row=0, column=0, sticky=W, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度范围(K 英文逗号分割 )")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)
        if not self.catObj.withTemp:
            self.T_input.insert(0, self.catObj.t)
            self.T_input.configure(state='readonly')
        self.T_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力范围(KPa 英文逗号分割)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比范围 (英文逗号分割)")
        lbl.grid(row=4, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=4, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="停留时间范围(英文逗号分割s)")
        lbl.grid(row=5, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=5, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=6, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=7, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=7, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="微分方程步长")
        lbl.grid(row=8, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.step_input = Entry(frame2)
        self.step_input.insert(0, 0.1)
        self.step_input.grid(row=8, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="待预测组分编号(,)")
        lbl.grid(row=9, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.target = Entry(frame2)
        self.target.insert(0, '5,6,7')
        self.target.grid(row=9, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="结果组成")
        lbl.grid(row=0, column=7, columnspan=2, rowspan=1, pady=4, padx=5, sticky=W)
        self.preResult_LB = Listbox(frame2)
        self.preResult_LB.grid(row=1, column=7, columnspan=2, rowspan=8, pady=4, padx=5, sticky=W)

        lbl = Label(frame2, text="最优温度:")
        lbl.grid(row=0, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestT = Entry(frame2)
        self.bestT.delete(0, 'end')
        self.bestT.configure(state='readonly')
        self.bestT.grid(row=0, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        lbl = Label(frame2, text="最优压力:")
        lbl.grid(row=1, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestP = Entry(frame2)
        self.bestP.delete(0, 'end')
        self.bestP.configure(state='readonly')
        self.bestP.grid(row=1, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        lbl = Label(frame2, text="最优剂油比:")
        lbl.grid(row=2, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestR = Entry(frame2)
        self.bestR.delete(0, 'end')
        self.bestR.configure(state='readonly')
        self.bestR.grid(row=2, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        lbl = Label(frame2, text="最优反应时间:")
        lbl.grid(row=3, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestTime = Entry(frame2)
        self.bestTime.delete(0, 'end')
        self.bestTime.configure(state='readonly')
        self.bestTime.grid(row=3, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        lbl = Label(frame2, text="目标结果:")
        lbl.grid(row=4, column=9, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.bestSum = Entry(frame2)
        self.bestSum.delete(0, 'end')
        self.bestSum.configure(state='readonly')
        self.bestSum.grid(row=4, column=11, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)
        cateDetailButton = Button(frame2, text="预测", command=self.doBest)
        cateDetailButton.grid(row=9, column=6, columnspan=2)

    def preUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=False)

        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(1, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.columnconfigure(10, pad=7)
        frame1.rowconfigure(5, weight=1)
        frame1.rowconfigure(5, pad=7)

        frame2.columnconfigure(8, pad=7, weight=1)
        frame2.rowconfigure(8, pad=7)

        lbl = Label(frame1, text="催化剂性质")
        lbl.grid(row=0, column=0, columnspan=8, rowspan=1, sticky=W, pady=4, padx=5)
        # K_Mat_Tree = ttk.Treeview(frame1)
        # K_Mat_Tree['show'] = 'headings'
        # K_Mat_Tree = self.makeMatrixUI(7, K_Mat_Tree, sourceDate.K_model)
        # K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=5, sticky=E + W + S + N, pady=4, padx=5)
        K_Mat_Tree = Text(frame1, height=18)
        self.makeMatrixUI(K_Mat_Tree, self.catObj)
        K_Mat_Tree.configure(state='normal')
        K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=6, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="优化方法:")
        lbl.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.optMethod)
        txt.configure(state='readonly')
        txt.grid(row=0, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="集总数:")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.n)
        txt.configure(state='readonly')
        txt.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="精确度:")
        lbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.tol)
        txt.configure(state='readonly')
        txt.grid(row=2, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        cateDetailButton = Button(frame1, text="查看催化剂详情")
        cateDetailButton.grid(row=3, column=8)
        # ________________________________________
        lbl = Label(frame2, text="待预测条件")
        lbl.grid(row=0, column=0, sticky=W, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度(K)")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)
        if not self.catObj.withTemp:
            self.T_input.insert(0, self.catObj.t)
            self.T_input.configure(state='readonly')
        self.T_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力(KPa)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比")
        lbl.grid(row=4, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=4, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="停留时间(s)")
        lbl.grid(row=5, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=5, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=6, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=7, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=7, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="微分方程步长")
        lbl.grid(row=8, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.step_input = Entry(frame2)
        self.step_input.insert(0, 0.1)
        self.step_input.grid(row=8, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)
        self.preResult_LB = Listbox(frame2)
        self.preResult_LB.grid(row=1, column=7, columnspan=2, rowspan=6, pady=4, padx=5)

        cateDetailButton = Button(frame2, text="预测", command=self.doPre)
        cateDetailButton.grid(row=8, column=7, columnspan=2)

    def cateUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame4 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame4.pack(fill=BOTH)

        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(0, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.rowconfigure(0, weight=1)

        lbl = Label(frame4, text="已输入温度组数")
        lbl.grid(row=0, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.varCountT = StringVar()
        self.countT = Message(frame4, textvariable=self.varCountT)
        self.varCountT.set('0')

        self.countT.grid(row=0, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        factor_Tree = ttk.Treeview(frame1)
        factor_Tree['show'] = 'headings'
        factor_Tree["columns"] = ['t_resid', 't', 'r_oil', 'p', 'Y0', 'Y_results', 'w_aro', 'w_nitro']
        #
        factor_Tree.heading("t", text="温度")
        factor_Tree.column("t", width=self.winfo_width() / 8)
        factor_Tree.heading("r_oil", text="剂油比")
        factor_Tree.column("r_oil", width=self.winfo_width() / 8)
        factor_Tree.heading("p", text="压力")
        factor_Tree.column("p", width=self.winfo_width() / 8)
        factor_Tree.heading("Y0", text="初始组成")
        factor_Tree.column("Y0", width=self.winfo_width() / 8)
        factor_Tree.heading("Y_results", text="产物组成")
        factor_Tree.column("Y_results", width=self.winfo_width() / 8)
        factor_Tree.heading("w_aro", text="重芳烃含量")
        factor_Tree.column("w_aro", width=self.winfo_width() / 8)
        factor_Tree.heading("w_nitro", text="碱氮含量")
        factor_Tree.column("w_nitro", width=self.winfo_width() / 8)
        factor_Tree.heading("t_resid", text="停留时间")
        factor_Tree.column("t_resid", width=self.winfo_width() / 8)
        factor_Tree.grid(row=0, column=0, pady=4, padx=5)
        self.factor_Tree = factor_Tree
        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame2.columnconfigure(0, weight=1)
        frame2.columnconfigure(8, weight=1)

        lbl = Label(frame2, text="停留时间(s)")
        lbl.grid(row=0, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=0, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度(K)")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)
        self.T_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力(KPa)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=0, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="产物组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.Y_results_input = Entry(frame2)
        self.Y_results_input.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=2, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=3, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=3, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="分子质量(逗号分割)")
        lbl.grid(row=4, column=4, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.Molmasses_input = Entry(frame2)
        self.Molmasses_input.grid(row=4, column=6, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)
        self.Molmasses_input.insert('0.8,1.1,1.8,0.2,0.2,0.2,0.11,0.016,0.042,0.056,0.05,0.012')
        addButton = Button(frame2, command=self.addFactors, text="添加条件")
        addButton.grid(row=9, column=2, sticky=E)

        self.newCatButton = Button(frame2, command=self.newCata, text="开始计算", state=DISABLED)
        self.newCatButton.grid(row=9, column=6, sticky=E)

    def graphUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=False)

        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(1, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.columnconfigure(10, pad=7)
        frame1.rowconfigure(5, weight=1)
        frame1.rowconfigure(5, pad=7)

        frame2.columnconfigure(8, pad=7, weight=1)
        frame2.columnconfigure(1, weight=1)
        frame2.columnconfigure(6, weight=1)
        frame2.rowconfigure(8, pad=7)

        lbl = Label(frame1, text="催化剂性质")
        lbl.grid(row=0, column=0, columnspan=8, rowspan=1, sticky=W, pady=4, padx=5)
        # K_Mat_Tree = ttk.Treeview(frame1)
        # K_Mat_Tree['show'] = 'headings'
        # K_Mat_Tree = self.makeMatrixUI(7, K_Mat_Tree, sourceDate.K_model)
        # K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=5, sticky=E + W + S + N, pady=4, padx=5)
        K_Mat_Tree = Text(frame1, height=18)
        self.makeMatrixUI(K_Mat_Tree, self.catObj)
        K_Mat_Tree.configure(state='normal')
        K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=6, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="优化方法:")
        lbl.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.optMethod)
        txt.configure(state='readonly')
        txt.grid(row=0, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="集总数:")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.n)
        txt.configure(state='readonly')
        txt.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="精确度:")
        lbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.tol)
        txt.configure(state='readonly')
        txt.grid(row=2, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        cateDetailButton = Button(frame1, text="查看催化剂详情")
        cateDetailButton.grid(row=3, column=8)
        # ________________________________________
        lbl = Label(frame2, text="待预测条件")
        lbl.grid(row=0, column=0, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度(K)")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)

        self.T_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力(KPa)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比")
        lbl.grid(row=4, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=4, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="停留时间(s)")
        lbl.grid(row=5, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=5, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=6, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=7, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=7, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="微分方程步长")
        lbl.grid(row=8, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        self.step_input = Entry(frame2)
        self.step_input.insert(0, 0.1)
        self.step_input.grid(row=8, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="图表设置")
        lbl.grid(row=0, column=6, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="条件变量")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.var = ttk.Combobox(frame2, textvariable=StringVar())
        if not self.catObj.withTemp:
            self.var['values'] = (u'压力', u'剂油比', u'停留时间')
            self.p_input.insert(0, 0)
            self.T_input.insert(0, self.catObj.t)
            self.T_input.configure(state='readonly')
            self.p_input.configure(state='readonly')
            self.lastVar = u'压力'
        else:
            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state='readonly')
            self.var['values'] = (u'温度', u'压力', u'剂油比', u'停留时间', u'温度+压力',u'温度+剂油比',u'剂油比+压力')
            self.lastVar = u'温度'
        self.var.bind('<<ComboboxSelected>>', self.onSelecetedVar)
        self.var.current(0)
        self.var.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        self.rangeLbl = Label(frame2, text="条件范围")
        self.rangeLbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        lbl = Label(frame2, text="上限")
        lbl.grid(row=3, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        lbl = Label(frame2, text="下限")
        lbl.grid(row=4, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.rangeMin = Entry(frame2)
        self.rangeMax = Entry(frame2)

        self.rangeMin.grid(row=3, column=8, columnspan=1, sticky=W, rowspan=1, pady=4, padx=5)
        self.rangeMax.grid(row=4, column=8, columnspan=1, sticky=W, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="结果集(英文逗号分割)")
        lbl.grid(row=5, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.chartResultId = Entry(frame2)
        self.chartResultId.insert(0, '1,2,3,4,5,6,7,8,9,10,11,12')
        self.chartResultId.grid(row=5, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="结果名(英文逗号分割\n尽量使用英文)")
        lbl.grid(row=6, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.chartResultName = Entry(frame2)
        #TODO,get the default value from lump model
        self.chartResultName.insert(0, 'HS,HA,HR,DIESEL,GS,GO,GA,DGAS,LO3,LO4,LPGD,COKE')
        self.chartResultName.grid(row=6, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="点数")
        lbl.grid(row=7, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.stepNum = Entry(frame2)
        self.stepNum.grid(row=7, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        cateDetailButton = Button(frame2, text="预测趋势", command=self.doChart)
        cateDetailButton.grid(row=8, column=6, columnspan=2)

    def onSelecetedVar(self, event):
        varName = self.var.get()
        if self.lastVar == u'温度':
            # u'温度',,,u'停留时间'
            self.T_input.configure(state="normal")
        elif self.lastVar == u'压力':
            self.p_input.configure(state="normal")
        elif self.lastVar == u'剂油比':
            self.roil_input.configure(state="normal")
        elif self.lastVar == u'停留时间':
            self.t_input.configure(state="normal")
        elif self.lastVar == u'温度+压力':
            self.T_input.configure(state="normal")
            self.p_input.configure(state="normal")
        elif self.lastVar == u'温度+剂油比':
            self.roil_input.configure(state="normal")
            self.T_input.configure(state="normal")
        elif self.lastVar == u'剂油比+压力':
            self.roil_input.configure(state="normal")
            self.p_input.configure(state="normal")

        if varName == u'温度':
            self.rangeLbl.config(text='条件范围')

            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state="readonly")
        elif varName == u'压力':
            self.rangeLbl.config(text='条件范围')

            self.p_input.delete(0, 'end')
            self.p_input.insert(0, 0)
            self.p_input.configure(state="readonly")
        elif varName == u'剂油比':
            self.rangeLbl.config(text='条件范围')

            self.roil_input.delete(0, 'end')
            self.roil_input.insert(0, 0)
            self.roil_input.configure(state="readonly")
        elif varName == u'停留时间':
            self.rangeLbl.config(text='条件范围')

            self.t_input.delete(0, 'end')
            self.t_input.insert(0, 0)
            self.t_input.configure(state="readonly")
        elif varName == u'温度+压力':
            self.rangeLbl.config(text='条件范围,格式:温度,压力')

            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state="readonly")
            self.p_input.delete(0, 'end')
            self.p_input.insert(0, 0)
            self.p_input.configure(state="readonly")
        elif varName == u'温度+剂油比':
            self.rangeLbl.config(text='条件范围,格式:温度,剂油比')
            self.roil_input.delete(0, 'end')
            self.roil_input.insert(0, 0)
            self.roil_input.configure(state="readonly")
            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state="readonly")

        elif varName == u'剂油比+压力':
            self.rangeLbl.config(text='条件范围,格式:剂油比,压力')
            self.roil_input.delete(0, 'end')
            self.roil_input.insert(0, 0)
            self.roil_input.configure(state="readonly")

            self.p_input.delete(0, 'end')
            self.p_input.insert(0, 0)
            self.p_input.configure(state="readonly")

        self.lastVar = varName

    def onNewCata(self):
        self.catFactors = {}
        ftypes = [('集总模型', '*.lp')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()
        # print flmakePreResultUI
        if fl != '':
            self.lumpObj = self.readFile(fl)
            print self.lumpObj
            self.cateUI()

    def onNewPre(self):
        ftypes = [('催化剂存档文件', '*.cat')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()
        print fl
        if fl != '':
            self.catObj = self.readFile(fl)
            self.preUI()
    def onNewBest(self):
        ftypes = [('催化剂存档文件', '*.cat')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()
        print fl
        if fl != '':
            self.catObj = self.readFile(fl)
            self.bestUI()
    def onNewGraph(self):
        ftypes = [('催化剂存档文件', '*.cat')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()
        print fl
        if fl != '':
            self.catObj = self.readFile(fl)
            self.graphUI()

    def saveCate(self):
        ftypes = [('催化剂存档文件', '*.cat')]
        filename = tkFileDialog.asksaveasfilename(title='保存催化剂存档文件', defaultextension='.cat', filetypes=ftypes)
        return filename

    def onHelp(self):
        mbox.showinfo("集总模型软件", "中国石油\n兰州化工研究中心")

    def doPre(self):
        catObj = self.catObj
        t_resid = float(self.t_input.get())
        p = float(self.p_input.get())
        Y0 = numpy.mat(self.Y0_input.get().split(',')).astype(numpy.float)
        const_r = 8.3145
        w_aro = float(self.ya_input.get())
        w_nitro = float(self.yn_input.get())
        t = float(self.T_input.get())
        r_oil = float(self.roil_input.get())
        stepLength = float(self.step_input.get())
        n = catObj.n
        print [t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n]
        result = newPre(catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, stepLength).tolist()[0]
        self.makePreResultUI(self.preResult_LB, result)
    def doBest(self):
        catObj = self.catObj
        t_resid = [float(self.t_input.get().split(',')[0]),float(self.t_input.get().split(',')[1])]
        p = [float(self.p_input.get().split(',')[0]),float(self.p_input.get().split(',')[1])]
        Y0 = numpy.mat(self.Y0_input.get().split(',')).astype(numpy.float)
        const_r = 8.3145
        w_aro = float(self.ya_input.get())
        w_nitro = float(self.yn_input.get())
        t = [float(self.T_input.get().split(',')[0]),float(self.T_input.get().split(',')[1])]
        r_oil = [float(self.roil_input.get().split(',')[0]),float(self.roil_input.get().split(',')[1])]
        stepLength = float(self.step_input.get())
        n = catObj.n
        target = self.target.get().split(',')
        print [t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n,target]
        result = newBest(catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, stepLength,target)
        self.bestP.configure(state='normal')
        self.bestT.configure(state='normal')
        self.bestR.configure(state='normal')
        self.bestTime.configure(state='normal')
        self.bestSum.configure(state='normal')
        self.bestP.insert('end',round(result['bestP'], 4))
        self.bestT.insert('end',round(result['bestT'], 4))
        self.bestR.insert('end',round(result['bestR'], 4))
        self.bestTime.insert('end',round(result['bestTime'], 4))
        self.bestSum.insert('end',round(result['sum'], 4))
        self.makePreResultUI(self.preResult_LB, result['Y'])
    def doChart(self):
        catObj = self.catObj
        t_resid = float(self.t_input.get())
        p = float(self.p_input.get())
        Y0 = numpy.mat(self.Y0_input.get().split(',')).astype(numpy.float)
        const_r = 8.3145
        w_aro = float(self.ya_input.get())
        w_nitro = float(self.yn_input.get())
        t = float(self.T_input.get())
        r_oil = float(self.roil_input.get())
        stepNum = int(self.stepNum.get())
        resultId = self.chartResultId.get()
        resultName = self.chartResultName.get()

        stepLength = float(self.step_input.get())
        n = catObj.n
        varName = ''
        if self.lastVar == u'温度':
            varName = 't'
            varMin = float(self.rangeMin.get())
            varMax = float(self.rangeMax.get())
        elif self.lastVar == u'压力':
            varName = 'p'
            varMin = float(self.rangeMin.get())
            varMax = float(self.rangeMax.get())
        elif self.lastVar == u'剂油比':
            varName = 'r'
            varMin = float(self.rangeMin.get())
            varMax = float(self.rangeMax.get())
        elif self.lastVar == u'停留时间':
            varName = 'time'
            varMin = float(self.rangeMin.get())
            varMax = float(self.rangeMax.get())
        elif self.lastVar == u'温度+压力':
            varName = 't,p'.split(',')
            varMin = self.rangeMin.get().split(',')
            varMax = self.rangeMax.get().split(',')
        elif self.lastVar == u'温度+剂油比':
            varName = 't,r'.split(',')
            varMin = self.rangeMin.get().split(',')
            varMax = self.rangeMax.get().split(',')
        elif self.lastVar == u'剂油比+压力':
            varName = 'r,p'.split(',')
            varMin = self.rangeMin.get().split(',')
            varMax = self.rangeMax.get().split(',')
        chartConfig = {}
        chartConfig['varName'] = varName
        chartConfig['stepNum'] = stepNum

        chartConfig['varMin'] = varMin
        chartConfig['varMax'] = varMax
        chartConfig['resultId'] = resultId
        chartConfig['resultName'] = resultName
        # t_resid=3
        # p=175
        # const_r=8.3145
        # Y0=mat([0.481,0.472,0.047,0,0,0,0])
        # w_aro=0.472
        # w_nitro=0
        # t=685
        # n=7
        # r_oil=8.79
        # chartConfig={'varName': 'time', 'varMax': 0.001, 'varMin': 15.0, 'resultId': '1,2,3,4,5,6,7', 'stepNum': 100,'resultName':u'Hs,Ha,Hr,柴油,汽油,气体,焦炭'}

        print chartConfig
        print [catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, chartConfig]
        if len(varName)>1:
            result = new3dChart(catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, chartConfig, stepLength)

        else:
            result = new2dChart(catObj, t_resid, p, Y0, const_r, w_aro, w_nitro, t, r_oil, n, chartConfig, stepLength)

    def addFactors(self):
        t_resid = float(self.t_input.get())
        p = float(self.p_input.get())
        Y0_raw = self.Y0_input.get()
        Y0 = numpy.mat(Y0_raw.split(',')).astype(numpy.float)
        Y_results_raw = self.Y_results_input.get()
        Y_results = numpy.mat(Y_results_raw.split(',')).astype(numpy.float)
        w_aro = float(self.ya_input.get())
        w_nitro = float(self.yn_input.get())
        t = float(self.T_input.get())
        r_oil = float(self.roil_input.get())
        self.Molmasses = numpy.mat(self.Molmasses_input.get().split(',')).astype(numpy.float)
        self.factor_Tree.insert('', END, values=[t_resid, t, r_oil, p, Y0_raw, Y_results_raw, w_aro, w_nitro])
        if self.catFactors.has_key(t):
            self.catFactors[t].append(
                {'t_resid': t_resid, 't': t, 'r_oil': r_oil, 'p': p, 'Y0': Y0, 'Y_results': Y_results, 'w_aro': w_aro,
                 'w_nitro': w_nitro})
        else:
            self.catFactors[t] = [
                {'t_resid': t_resid, 't': t, 'r_oil': r_oil, 'p': p, 'Y0': Y0, 'Y_results': Y_results, 'w_aro': w_aro,
                 'w_nitro': w_nitro}]
        print self.catFactors
        self.varCountT.set(len(self.catFactors))
        self.Molmasses_input.configure(state='readonly')
        self.newCatButton.configure(state='active')

    def newCata(self):
        filename = self.saveCate()
        print filename
        if len(self.catFactors) == 1:
            newCatNoKa(filename, self.lumpObj, 1, 0, 1, self.lumpObj, self.Molmasses, self.catFactors.values()[0],
                       'L-BFGS-B',
                       1e-5, self.lumpObj.shape[0])
        else:
            newCatWithKa(filename, self.lumpObj, 1, 0, 1, self.lumpObj, self.Molmasses, self.catFactors, 'L-BFGS-B',
                         1e-5,
                         self.lumpObj.shape[0])

    def makeMatrixUI(self, targetTree, catObj):
        n = catObj.n
        if not catObj.withTemp:
            targetTree.insert('end', '催化剂模型是在同一温度下,只能计算K\n------------------\nK=\n')
            K = numpy.around(self.makeMatrixByResult(catObj.K_model, catObj.X0_result, catObj.n)['K_result'], 4)
            self.makeMatrixOutput(n, targetTree, K)
            targetTree.insert('end', '\n------------------\n重芳烃影响因数:\n')
            targetTree.insert('end', self.makeMatrixByResult(catObj.K_model, catObj.X0_result, catObj.n)['Ka'])
            targetTree.insert('end', '\n------------------\n碱氮影响因数:\n')
            targetTree.insert('end', self.makeMatrixByResult(catObj.K_model, catObj.X0_result, catObj.n)['Kn'])
            targetTree.insert('end', '\n------------------\n')

        else:
            K = self.makeMatrixByResult(catObj.K_model, catObj.X0_result, catObj.n)['K_result']
            print catObj.X0_result
            Ka = numpy.around(self.makeMatrixByResult(catObj.K_model, catObj.Ka, catObj.n)['K_result'], 4)
            print catObj.Ka
            Ea = numpy.around(self.makeMatrixByResult(catObj.K_model, catObj.Ea, catObj.n)['K_result'], 4)
            print catObj.Ea
            targetTree.insert('end', '\n------------------\nK=\n')
            print len(K)
            for i in K:
                self.makeMatrixOutput(n, targetTree, numpy.round(i, 4))
                targetTree.insert('end', '\n------------------\n')
            targetTree.insert('end', '\n------------------\nKa=\n')
            self.makeMatrixOutput(n, targetTree, Ka)
            targetTree.insert('end', '\n------------------\n')
            targetTree.insert('end', '\n------------------\nEa=\n')
            self.makeMatrixOutput(n, targetTree, Ea)
            targetTree.insert('end', '\n------------------\n')

    def makeMatrixOutput(self, n, targetTree, mat):
        for i in range(n):
            targetTree.insert('end', ','.join(mat[i].astype(numpy.string_).tolist()))
            targetTree.insert('end', '\n')
        return targetTree

    def makeMatrixByResult(self, K_model, result, n):
        if type(result) != type([]):
            K = result[:-3].tolist()
            args = result[-3:]
            K_raw_result = []
            for i in K_model.T.flat:
                if i:
                    K_raw_result.append(K.pop(0))
                else:
                    K_raw_result.append(0)
            K_result = reshape(K_raw_result, (n, n)).T.T.T
            ka_result, kn_result, cata_result = args
            return {'K_result': K_result, 'ka_result': ka_result, 'kn_result': kn_result, 'cata_result': cata_result}
        else:
            K_results = []

            args = result[0][-3:]
            for i in result:
                K = i[:-3].tolist()
                K_raw_result = []
                for i in K_model.T.flat:
                    if i:
                        K_raw_result.append(K.pop(0))
                    else:
                        K_raw_result.append(0)
                K_result = reshape(K_raw_result, (n, n)).T.T.T
                K_results.append(K_result)
            ka_result, kn_result, cata_result = args
            return {'K_result': K_results, 'ka_result': ka_result, 'kn_result': kn_result,
                    'cata_result': cata_result}

    def makePreResultUI(self, target, result):
        target.delete(0, END)
        if type(result)!=type([]):
            result=result.tolist()[0]
        for i in result:
            target.insert(END, round(i, 3))
        return target

    def readFile(self, filename):
        f = open(filename, "r")
        obj = pickle.load(f)
        return obj
Example #25
0
class SearchBox(Frame):
    def __init__(self, master, entry_width=30, entry_font=None, entry_background="white", entry_highlightthickness=1, button_text="Search", button_ipadx=10, button_background="#009688", button_foreground="white", button_font=None, opacity=0.8, placeholder=None, placeholder_font=None, placeholder_color="grey", spacing=3, command=None):
        Frame.__init__(self, master)
        
        self._command = command

        self.entry = Entry(self, width=entry_width, background=entry_background, highlightcolor=button_background, highlightthickness=entry_highlightthickness)
        self.entry.pack(side=LEFT, fill=BOTH, ipady=1, padx=(0,spacing))
        
        if entry_font:
            self.entry.configure(font=entry_font)

        if placeholder:
            add_placeholder_to(self.entry, placeholder, color=placeholder_color, font=placeholder_font)

        self.entry.bind("<Escape>", lambda event: self.entry.nametowidget(".").focus())
        self.entry.bind("<Return>", self._on_execute_command)

        opacity = float(opacity)

        if button_background.startswith("#"):
            r,g,b = hex2rgb(button_background)
        else:
            # Color name
            r,g,b = master.winfo_rgb(button_background)

        r = int(opacity*r)
        g = int(opacity*g)
        b = int(opacity*b)

        if r <= 255 and g <= 255 and b <=255:
            self._button_activebackground = '#%02x%02x%02x' % (r,g,b)
        else:
            self._button_activebackground = '#%04x%04x%04x' % (r,g,b)

        self._button_background = button_background

        self.button_label = Label(self, text=button_text, background=button_background, foreground=button_foreground, font=button_font)
        if entry_font:
            self.button_label.configure(font=button_font)
            
        self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx)
        
        self.button_label.bind("<Enter>", self._state_active)
        self.button_label.bind("<Leave>", self._state_normal)

        self.button_label.bind("<ButtonRelease-1>", self._on_execute_command)

    def get_text(self):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            if entry.placeholder_state.contains_placeholder:
                return ""
            else:
                return entry.get()
        else:
            return entry.get()
        
    def set_text(self, text):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            entry.placeholder_state.contains_placeholder = False

        entry.delete(0, END)
        entry.insert(0, text)
        
    def clear(self):
        self.entry_var.set("")
        
    def focus(self):
        self.entry.focus()

    def _on_execute_command(self, event):
        text = self.get_text()
        self._command(text)

    def _state_normal(self, event):
        self.button_label.configure(background=self._button_background)

    def _state_active(self, event):
        self.button_label.configure(background=self._button_activebackground)
Example #26
0
    def graphUI(self):
        self.frame0.destroy()
        self.initUIRoot()
        frame1 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame1.pack(fill=BOTH, expand=False)

        frame2 = Frame(self.frame0, relief=RAISED, borderwidth=1)
        frame2.pack(fill=BOTH, expand=True)

        frame1.columnconfigure(1, weight=1)
        # frame1.columnconfigure(9, weight=1)
        frame1.columnconfigure(10, pad=7)
        frame1.rowconfigure(5, weight=1)
        frame1.rowconfigure(5, pad=7)

        frame2.columnconfigure(8, pad=7, weight=1)
        frame2.columnconfigure(1, weight=1)
        frame2.columnconfigure(6, weight=1)
        frame2.rowconfigure(8, pad=7)

        lbl = Label(frame1, text="催化剂性质")
        lbl.grid(row=0, column=0, columnspan=8, rowspan=1, sticky=W, pady=4, padx=5)
        # K_Mat_Tree = ttk.Treeview(frame1)
        # K_Mat_Tree['show'] = 'headings'
        # K_Mat_Tree = self.makeMatrixUI(7, K_Mat_Tree, sourceDate.K_model)
        # K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=5, sticky=E + W + S + N, pady=4, padx=5)
        K_Mat_Tree = Text(frame1, height=18)
        self.makeMatrixUI(K_Mat_Tree, self.catObj)
        K_Mat_Tree.configure(state='normal')
        K_Mat_Tree.grid(row=1, column=0, columnspan=6, rowspan=6, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="优化方法:")
        lbl.grid(row=0, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.optMethod)
        txt.configure(state='readonly')
        txt.grid(row=0, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="集总数:")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.n)
        txt.configure(state='readonly')
        txt.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        lbl = Label(frame1, text="精确度:")
        lbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)
        txt = Entry(frame1)
        txt.insert(0, self.catObj.tol)
        txt.configure(state='readonly')
        txt.grid(row=2, column=8, columnspan=2, rowspan=1, sticky=E + W + S + N, pady=4, padx=5)

        cateDetailButton = Button(frame1, text="查看催化剂详情")
        cateDetailButton.grid(row=3, column=8)
        # ________________________________________
        lbl = Label(frame2, text="待预测条件")
        lbl.grid(row=0, column=0, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="初始组成(<1 英文逗号分割):")
        lbl.grid(row=1, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.Y0_input = Entry(frame2)
        self.Y0_input.grid(row=1, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="温度(K)")
        lbl.grid(row=2, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.T_input = Entry(frame2)

        self.T_input.grid(row=2, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="压力(KPa)")
        lbl.grid(row=3, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.p_input = Entry(frame2)
        self.p_input.grid(row=3, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="剂油比")
        lbl.grid(row=4, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.roil_input = Entry(frame2)
        self.roil_input.grid(row=4, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="停留时间(s)")
        lbl.grid(row=5, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.t_input = Entry(frame2)
        self.t_input.grid(row=5, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="碱氮含量(<1)")
        lbl.grid(row=6, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.yn_input = Entry(frame2)
        self.yn_input.insert(0, 0.0)
        self.yn_input.grid(row=6, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="重芳烃含量(<1)")
        lbl.grid(row=7, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.ya_input = Entry(frame2)
        self.ya_input.grid(row=7, column=2, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="微分方程步长")
        lbl.grid(row=8, column=0, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)

        self.step_input = Entry(frame2)
        self.step_input.insert(0, 0.1)
        self.step_input.grid(row=8, column=2, columnspan=3, rowspan=1, sticky=E, pady=4, padx=5)

        lbl = Label(frame2, text="图表设置")
        lbl.grid(row=0, column=6, columnspan=5, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="条件变量")
        lbl.grid(row=1, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.var = ttk.Combobox(frame2, textvariable=StringVar())
        if not self.catObj.withTemp:
            self.var['values'] = (u'压力', u'剂油比', u'停留时间')
            self.p_input.insert(0, 0)
            self.T_input.insert(0, self.catObj.t)
            self.T_input.configure(state='readonly')
            self.p_input.configure(state='readonly')
            self.lastVar = u'压力'
        else:
            self.T_input.delete(0, 'end')
            self.T_input.insert(0, 0)
            self.T_input.configure(state='readonly')
            self.var['values'] = (u'温度', u'压力', u'剂油比', u'停留时间', u'温度+压力',u'温度+剂油比',u'剂油比+压力')
            self.lastVar = u'温度'
        self.var.bind('<<ComboboxSelected>>', self.onSelecetedVar)
        self.var.current(0)
        self.var.grid(row=1, column=8, columnspan=2, rowspan=1, sticky=W, pady=4, padx=5)

        self.rangeLbl = Label(frame2, text="条件范围")
        self.rangeLbl.grid(row=2, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        lbl = Label(frame2, text="上限")
        lbl.grid(row=3, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        lbl = Label(frame2, text="下限")
        lbl.grid(row=4, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.rangeMin = Entry(frame2)
        self.rangeMax = Entry(frame2)

        self.rangeMin.grid(row=3, column=8, columnspan=1, sticky=W, rowspan=1, pady=4, padx=5)
        self.rangeMax.grid(row=4, column=8, columnspan=1, sticky=W, rowspan=1, pady=4, padx=5)

        lbl = Label(frame2, text="结果集(英文逗号分割)")
        lbl.grid(row=5, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.chartResultId = Entry(frame2)
        self.chartResultId.insert(0, '1,2,3,4,5,6,7,8,9,10,11,12')
        self.chartResultId.grid(row=5, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="结果名(英文逗号分割\n尽量使用英文)")
        lbl.grid(row=6, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.chartResultName = Entry(frame2)
        #TODO,get the default value from lump model
        self.chartResultName.insert(0, 'HS,HA,HR,DIESEL,GS,GO,GA,DGAS,LO3,LO4,LPGD,COKE')
        self.chartResultName.grid(row=6, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        lbl = Label(frame2, text="点数")
        lbl.grid(row=7, column=6, columnspan=2, rowspan=1, sticky=E, pady=4, padx=5)
        self.stepNum = Entry(frame2)
        self.stepNum.grid(row=7, column=8, columnspan=3, rowspan=1, sticky=W, pady=4, padx=5)

        cateDetailButton = Button(frame2, text="预测趋势", command=self.doChart)
        cateDetailButton.grid(row=8, column=6, columnspan=2)
Example #27
0
class Tool_Path_Generator:
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#e6e6e6'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        font11 = "-size 15 -weight normal -slant roman "  \
            "-underline 0 -overstrike 0"

        self.axial_length = DoubleVar()
        self.printbed_diameter = DoubleVar()
        self.final_diameter = DoubleVar()
        self.filament_width_og = DoubleVar()
        self.helix_angle = DoubleVar()
        self.smear_factor = DoubleVar()
        self.flow_rate = DoubleVar()
        self.uv_offset = DoubleVar()
        self.use_strong_pattern = BooleanVar()

        self.axial_length.set(200.0)
        self.printbed_diameter.set(10.0)
        self.final_diameter.set(15.0)
        self.filament_width_og.set(0.41)
        self.helix_angle.set(45.0)
        self.smear_factor.set(100.0)
        self.flow_rate.set(0.0015)
        self.uv_offset.set(32.5)
        self.use_strong_pattern.set(True)

        top.geometry("700x550")
        top.title("SkelePrint Tool Path Generator")
        top.configure(background="#e6e6e6")
        top.configure(highlightbackground="#e6e6e6")
        top.configure(highlightcolor="black")

        self.Label7 = Label(top)
        self.Label7.grid(row=0, column=0, sticky=W)
        self.Label7.configure(background="#e6e6e6")
        self.Label7.configure(font=font11)
        self.Label7.configure(foreground="#000000")
        self.Label7.configure(text='''SkelePrint Tool Path Generator''')

        self.Labelframe1 = LabelFrame(top)
        self.Labelframe1.grid(row=1, column=0, sticky=N+S)
        self.Labelframe1.configure(relief=GROOVE)
        self.Labelframe1.configure(foreground="black")
        self.Labelframe1.configure(text='''Dimensions''')
        self.Labelframe1.configure(background="#e6e6e6")
        self.Labelframe1.configure(highlightbackground="#e6e6e6")
        self.Labelframe1.configure(highlightcolor="black")

        self.axial_length_entry = Entry(self.Labelframe1)
        self.axial_length_entry.grid(row=0, column=1)
        self.axial_length_entry.configure(background="white")
        self.axial_length_entry.configure(font="TkFixedFont")
        self.axial_length_entry.configure(foreground="#000000")
        self.axial_length_entry.configure(highlightbackground="#e6e6e6")
        self.axial_length_entry.configure(highlightcolor="black")
        self.axial_length_entry.configure(insertbackground="black")
        self.axial_length_entry.configure(selectbackground="#c4c4c4")
        self.axial_length_entry.configure(selectforeground="black")
        self.axial_length_entry.configure(textvariable=self.axial_length)

        self.Label1 = Label(self.Labelframe1)
        self.Label1.grid(row=0, column=0, sticky=E)
        self.Label1.configure(activebackground="#e6e6e6")
        self.Label1.configure(activeforeground="black")
        self.Label1.configure(background="#e6e6e6")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(highlightbackground="#e6e6e6")
        self.Label1.configure(highlightcolor="black")
        self.Label1.configure(text='''Axial Length''')

        self.Label2 = Label(self.Labelframe1)
        self.Label2.grid(row=0, column=2, sticky=W)
        self.Label2.configure(activebackground="#e6e6e6")
        self.Label2.configure(activeforeground="black")
        self.Label2.configure(background="#e6e6e6")
        self.Label2.configure(disabledforeground="#e6e6e6")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(highlightbackground="#e6e6e6")
        self.Label2.configure(highlightcolor="black")
        self.Label2.configure(text='''mm''')

        self.Label3 = Label(self.Labelframe1)
        self.Label3.grid(row=1, column=0, sticky=E)
        self.Label3.configure(activebackground="#e6e6e6")
        self.Label3.configure(activeforeground="black")
        self.Label3.configure(background="#e6e6e6")
        self.Label3.configure(foreground="#000000")
        self.Label3.configure(highlightbackground="#e6e6e6")
        self.Label3.configure(highlightcolor="black")
        self.Label3.configure(text='''Printbed Diameter''')

        self.Entry2 = Entry(self.Labelframe1)
        self.Entry2.grid(row=1, column=1)
        self.Entry2.configure(background="white")
        self.Entry2.configure(font="TkFixedFont")
        self.Entry2.configure(foreground="#000000")
        self.Entry2.configure(highlightbackground="#e6e6e6")
        self.Entry2.configure(highlightcolor="black")
        self.Entry2.configure(insertbackground="black")
        self.Entry2.configure(selectbackground="#c4c4c4")
        self.Entry2.configure(selectforeground="black")
        self.Entry2.configure(textvariable=self.printbed_diameter)

        self.Label4 = Label(self.Labelframe1)
        self.Label4.grid(row=1, column=2, sticky=W)
        self.Label4.configure(activebackground="#e6e6e6")
        self.Label4.configure(activeforeground="black")
        self.Label4.configure(background="#e6e6e6")
        self.Label4.configure(foreground="#000000")
        self.Label4.configure(highlightbackground="#e6e6e6")
        self.Label4.configure(highlightcolor="black")
        self.Label4.configure(text='''mm''')

        self.Label5 = Label(self.Labelframe1)
        self.Label5.grid(row=2, column=0, sticky=E)
        self.Label5.configure(activebackground="#e6e6e6")
        self.Label5.configure(activeforeground="black")
        self.Label5.configure(background="#e6e6e6")
        self.Label5.configure(foreground="#000000")
        self.Label5.configure(highlightbackground="#e6e6e6")
        self.Label5.configure(highlightcolor="black")
        self.Label5.configure(text='''Final Print Diameter''')

        self.final_diameter_entry = Entry(self.Labelframe1)
        self.final_diameter_entry.grid(row=2, column=1)
        self.final_diameter_entry.configure(background="white")
        self.final_diameter_entry.configure(font="TkFixedFont")
        self.final_diameter_entry.configure(foreground="#000000")
        self.final_diameter_entry.configure(highlightbackground="#e6e6e6")
        self.final_diameter_entry.configure(highlightcolor="black")
        self.final_diameter_entry.configure(insertbackground="black")
        self.final_diameter_entry.configure(selectbackground="#c4c4c4")
        self.final_diameter_entry.configure(selectforeground="black")
        self.final_diameter_entry.configure(textvariable=self.final_diameter)

        self.Label6 = Label(self.Labelframe1)
        self.Label6.grid(row=2, column=2, sticky=W)
        self.Label6.configure(activebackground="#e6e6e6")
        self.Label6.configure(activeforeground="black")
        self.Label6.configure(background="#e6e6e6")
        self.Label6.configure(foreground="#000000")
        self.Label6.configure(highlightbackground="#e6e6e6")
        self.Label6.configure(highlightcolor="black")
        self.Label6.configure(text='''mm''')

        self.Entry4 = Entry(self.Labelframe1)
        self.Entry4.grid(row=3, column=1)
        self.Entry4.configure(background="white")
        self.Entry4.configure(font="TkFixedFont")
        self.Entry4.configure(foreground="#000000")
        self.Entry4.configure(highlightbackground="#e6e6e6")
        self.Entry4.configure(highlightcolor="black")
        self.Entry4.configure(insertbackground="black")
        self.Entry4.configure(selectbackground="#c4c4c4")
        self.Entry4.configure(selectforeground="black")
        self.Entry4.configure(textvariable=self.filament_width_og)

        self.Label7 = Label(self.Labelframe1)
        self.Label7.grid(row=3, column=2, sticky=W)
        self.Label7.configure(activebackground="#e6e6e6")
        self.Label7.configure(activeforeground="black")
        self.Label7.configure(background="#e6e6e6")
        self.Label7.configure(foreground="#000000")
        self.Label7.configure(highlightbackground="#e6e6e6")
        self.Label7.configure(highlightcolor="black")
        self.Label7.configure(text='''mm''')

        self.Label8 = Label(self.Labelframe1)
        self.Label8.grid(row=3, column=0, sticky=E)
        self.Label8.configure(activebackground="#e6e6e6")
        self.Label8.configure(activeforeground="black")
        self.Label8.configure(background="#e6e6e6")
        self.Label8.configure(foreground="#000000")
        self.Label8.configure(highlightbackground="#e6e6e6")
        self.Label8.configure(highlightcolor="black")
        self.Label8.configure(text='''Filament Width''')

        self.tip = Label(self.Labelframe1, width=300, height=300)

        __location__ = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__)))

        img = Image.open(os.path.join(__location__, 'dimensions.png'))
        one = ImageTk.PhotoImage(img)

        self.tip = Label(self.Labelframe1, image=one)
        self.tip.image = one
        self.tip.configure(background="#e6e6e6")
        self.tip.grid(row=4, columnspan=3)

        self.Labelframe2 = LabelFrame(top)
        self.Labelframe2.grid(row=1, column=1, sticky=N+S)
        self.Labelframe2.configure(relief=GROOVE)
        self.Labelframe2.configure(foreground="black")
        self.Labelframe2.configure(text='''Print Properties''')
        self.Labelframe2.configure(background="#e6e6e6")
        self.Labelframe2.configure(highlightbackground="#e6e6e6")
        self.Labelframe2.configure(highlightcolor="black")

        self.Label9 = Label(self.Labelframe2)
        self.Label9.grid(row=0, column=0, sticky=E)
        self.Label9.configure(activebackground="#e6e6e6")
        self.Label9.configure(activeforeground="black")
        self.Label9.configure(background="#e6e6e6")
        self.Label9.configure(foreground="#000000")
        self.Label9.configure(highlightbackground="#e6e6e6")
        self.Label9.configure(highlightcolor="black")
        self.Label9.configure(text='''Helix Angle''')

        self.Entry5 = Entry(self.Labelframe2)
        self.Entry5.grid(row=0, column=1)
        self.Entry5.configure(background="white")
        self.Entry5.configure(font="TkFixedFont")
        self.Entry5.configure(foreground="#000000")
        self.Entry5.configure(highlightbackground="#e6e6e6")
        self.Entry5.configure(highlightcolor="black")
        self.Entry5.configure(insertbackground="black")
        self.Entry5.configure(selectbackground="#c4c4c4")
        self.Entry5.configure(selectforeground="black")
        self.Entry5.configure(textvariable=self.helix_angle)

        self.Label10 = Label(self.Labelframe2)
        self.Label10.grid(row=0, column=2, sticky=W)
        self.Label10.configure(activebackground="#e6e6e6")
        self.Label10.configure(activeforeground="black")
        self.Label10.configure(background="#e6e6e6")
        self.Label10.configure(foreground="#000000")
        self.Label10.configure(highlightbackground="#e6e6e6")
        self.Label10.configure(highlightcolor="black")
        self.Label10.configure(text='''degrees [0 - 90]''')

        self.strong_targeter_button = Radiobutton(self.Labelframe2)
        self.strong_targeter_button.grid(row=1, column=0, sticky=E)
        self.strong_targeter_button.configure(variable=self.use_strong_pattern)
        self.strong_targeter_button.configure(value=True)
        self.strong_targeter_button.configure(activebackground="#e6e6e6")
        self.strong_targeter_button.configure(activeforeground="black")
        self.strong_targeter_button.configure(background="#e6e6e6")
        self.strong_targeter_button.configure(foreground="#000000")
        self.strong_targeter_button.configure(highlightbackground="#e6e6e6")
        self.strong_targeter_button.configure(highlightcolor="black")

        self.strong_targeter_label = Label(self.Labelframe2)
        self.strong_targeter_label.grid(row=1, column=1, sticky=W)
        self.strong_targeter_label.configure(activebackground="#e6e6e6")
        self.strong_targeter_label.configure(activeforeground="black")
        self.strong_targeter_label.configure(background="#e6e6e6")
        self.strong_targeter_label.configure(foreground="#000000")
        self.strong_targeter_label.configure(highlightbackground="#e6e6e6")
        self.strong_targeter_label.configure(highlightcolor="black")
        self.strong_targeter_label.configure(text="Strong angle pattern")

        self.default_targeter_button = Radiobutton(self.Labelframe2)
        self.default_targeter_button.grid(row=2, column=0, sticky=E)
        self.default_targeter_button.configure(activebackground="#e6e6e6")
        self.default_targeter_button.configure(activeforeground="black")
        self.default_targeter_button.configure(background="#e6e6e6")
        self.default_targeter_button.configure(foreground="#000000")
        self.default_targeter_button.configure(highlightbackground="#e6e6e6")
        self.default_targeter_button.configure(highlightcolor="black")
        self.default_targeter_button.configure(
                variable=self.use_strong_pattern)
        self.default_targeter_button.configure(value=False)

        self.default_targeter_label = Label(self.Labelframe2)
        self.default_targeter_label.grid(row=2, column=1, sticky=W)
        self.default_targeter_label.configure(activebackground="#e6e6e6")
        self.default_targeter_label.configure(activeforeground="black")
        self.default_targeter_label.configure(background="#e6e6e6")
        self.default_targeter_label.configure(foreground="#000000")
        self.default_targeter_label.configure(highlightbackground="#e6e6e6")
        self.default_targeter_label.configure(highlightcolor="black")
        self.default_targeter_label.configure(text="Default angle pattern")

        self.Scale1 = Scale(self.Labelframe2)
        self.Scale1.grid(row=5, column=1, columnspan=2, sticky=S+W)
        self.Scale1.configure(activebackground="#e6e6e6")
        self.Scale1.configure(background="#e6e6e6")
        self.Scale1.configure(font="TkTextFont")
        self.Scale1.configure(foreground="#000000")
        self.Scale1.configure(from_="5.0")
        self.Scale1.configure(highlightbackground="#d9d9d9")
        self.Scale1.configure(highlightcolor="black")
        self.Scale1.configure(length="150")
        self.Scale1.configure(orient="horizontal")
        self.Scale1.configure(resolution="5.0")
        self.Scale1.configure(troughcolor="#d9d9d9")
        self.Scale1.configure(variable=self.smear_factor)

        self.Label8 = Label(self.Labelframe2)
        self.Label8.grid(row=3, column=0, sticky=E)
        self.Label8.configure(background="#e6e6e6")
        self.Label8.configure(foreground="#000000")
        self.Label8.configure(text='''Flow rate''')

        self.Entry6 = Entry(self.Labelframe2)
        self.Entry6.grid(row=3, column=1)
        self.Entry6.configure(background="white")
        self.Entry6.configure(font="TkFixedFont")
        self.Entry6.configure(foreground="#000000")
        self.Entry6.configure(highlightbackground="#e6e6e6")
        self.Entry6.configure(highlightcolor="black")
        self.Entry6.configure(insertbackground="black")
        self.Entry6.configure(selectbackground="#c4c4c4")
        self.Entry6.configure(selectforeground="black")
        self.Entry6.configure(textvariable=self.flow_rate)

        self.Label12 = Label(self.Labelframe2)
        self.Label12.grid(row=3, column=2, sticky=W)
        self.Label12.configure(activebackground="#e6e6e6")
        self.Label12.configure(activeforeground="black")
        self.Label12.configure(background="#e6e6e6")
        self.Label12.configure(foreground="#000000")
        self.Label12.configure(highlightbackground="#d9d9d9")
        self.Label12.configure(highlightcolor="black")
        self.Label12.configure(text='''cm^3 / s''')

        self.uv_label = Label(self.Labelframe2)
        self.uv_label.grid(row=4, column=0, sticky=E)
        self.uv_label.configure(activebackground="#e6e6e6")
        self.uv_label.configure(activeforeground="black")
        self.uv_label.configure(background="#e6e6e6")
        self.uv_label.configure(foreground="#000000")
        self.uv_label.configure(highlightbackground="#d9d9d9")
        self.uv_label.configure(highlightcolor="black")
        self.uv_label.configure(text="UV Distance")

        self.uv_entry = Entry(self.Labelframe2)
        self.uv_entry.grid(row=4, column=1)
        self.uv_entry.configure(background="white")
        self.uv_entry.configure(font="TkFixedFont")
        self.uv_entry.configure(foreground="#000000")
        self.uv_entry.configure(highlightbackground="#e6e6e6")
        self.uv_entry.configure(highlightcolor="black")
        self.uv_entry.configure(insertbackground="black")
        self.uv_entry.configure(selectbackground="#c4c4c4")
        self.uv_entry.configure(selectforeground="black")
        self.uv_entry.configure(textvariable=self.uv_offset)

        self.uv_label_2 = Label(self.Labelframe2)
        self.uv_label_2.grid(row=4, column=2, sticky=W)
        self.uv_label_2.configure(activebackground="#e6e6e6")
        self.uv_label_2.configure(activeforeground="black")
        self.uv_label_2.configure(background="#e6e6e6")
        self.uv_label_2.configure(foreground="#000000")
        self.uv_label_2.configure(highlightbackground="#d9d9d9")
        self.uv_label_2.configure(highlightcolor="black")
        self.uv_label_2.configure(text='''mm''')

        self.Label11 = Label(self.Labelframe2)
        self.Label11.grid(row=5, column=0, sticky=S+E)
        self.Label11.configure(activebackground="#e6e6e6")
        self.Label11.configure(activeforeground="black")
        self.Label11.configure(background="#e6e6e6")
        self.Label11.configure(foreground="#000000")
        self.Label11.configure(highlightbackground="#d9d9d9")
        self.Label11.configure(highlightcolor="black")
        self.Label11.configure(text='''Layer Height %''')

        self.Label13 = Label(self.Labelframe2)
        self.Label13.grid(row=6, columnspan=3)
        self.Label13.configure(activebackground="#f9f9f9")
        self.Label13.configure(activeforeground="black")
        self.Label13.configure(background="#e6e6e6")
        self.Label13.configure(foreground="#000000")
        self.Label13.configure(highlightbackground="#d9d9d9")
        self.Label13.configure(highlightcolor="black")
        self.Label13.configure(text='''caution: layer height % is experimental
default = 100% (ie. layer height = filament width)''')

        self.Message1 = Message(self.Labelframe2)
        self.Message1.grid(row=8, columnspan=3)
        self.Message1.configure(anchor=N)
        self.Message1.configure(background="#e6e6e6")
        self.Message1.configure(foreground="#000000")
        self.Message1.configure(highlightbackground="#e6e6e6")
        self.Message1.configure(highlightcolor="black")
        self.Message1.configure(text='''Helix Angle Conditions:
If the angle is > 90, it will be set to 90 degrees

If angle is < 0, it will be set to 0 degrees

If angle = 0, the layer will consist of a single helix printed as close \
together as possible

If angle = 90, the layer will consist of many straight lines''')

        self.tip2 = Label(self.Labelframe2, width=300, height=91)

        img2 = Image.open(os.path.join(__location__, 'theta.jpg'))
        two = ImageTk.PhotoImage(img2)

        self.tip2 = Label(self.Labelframe2, image=two)
        self.tip2.image = two
        self.tip2.configure(background="#e6e6e6")
        self.tip2.grid(row=7, columnspan=3)

        self.Label8 = Label(top)
        self.Label8.grid(row=5, columnspan=2)
        self.Label8.configure(background="#e6e6e6")
        self.Label8.configure(foreground="#000000")
        self.Label8.configure(text='''G Code file will be saved on your Desktop under:
"gcode/timestamp_skeleprint_gcode.gcode"''')

        self.Button1 = Button(top)
        self.Button1.grid(row=2, columnspan=2)
        self.Button1.configure(activebackground="#e6e6e6")
        self.Button1.configure(activeforeground="#e6e6e6")
        self.Button1.configure(background="#e6e6e6")
        self.Button1.configure(command=lambda: tpg_gui_support.tpg(
            self.axial_length.get(),
            self.filament_width_og.get(),
            self.printbed_diameter.get(),
            self.final_diameter.get(),
            self.helix_angle.get(),
            self.smear_factor.get(),
            self.flow_rate.get(),
            self.uv_offset.get(),
            self.use_strong_pattern.get()))
        self.Button1.configure(foreground="#000000")
        self.Button1.configure(highlightbackground="#e6e6e6")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(relief=RAISED)
        self.Button1.configure(text='''Generate G Code''')

        self.menubar = Menu(top, font="TkMenuFont", bg=_bgcolor, fg=_fgcolor)
        top.configure(menu=self.menubar)
Example #28
0
class EMNN():
    def __init__(self, conn):
        conn.gui = True
        queue = self.queue = Queue.Queue()
        conn.queue = queue
        self.conn = conn

    def startgui(self):
        self.root = root = Tk()
        root.title('SIMAPSE - Simulation Maps for Ecological Niche Modelling')
        root.geometry('695x445+375+115')
        root.tk.call('encoding', 'system', 'utf-8')
        root.configure(bg='#d9d9d9')
        root.resizable(width='false', height='false')
        self.gui()
        self.root.after(100, self.periodicUpdate)
        root.mainloop()

    def gui(self):
        from Tkinter import Button, Entry, Frame, Label, Checkbutton, \
                            Scrollbar, Text, IntVar, StringVar, OptionMenu

        self.dir_project = ''
        self.folds = 0
        self.func = ""
        self.aucfilter = IntVar()

        self.lightgray = '#d9d9d9'
        self.darkgray = '#d3d3d3'

        self.normaltext = ("Helvetica", -10)
        self.boldtext = ("Helvetica", -10, "bold")
        self.bigtext = ("Helvetica", -12, "bold")
        self.smalltext = ("Helvetica", -9)

        self.butData = Button(self.root)
        self.butData.place(in_=self.root, x=5, y=5)
        self.butData.configure(height=1,
                               width=10,
                               text="Data File",
                               font=self.normaltext,
                               highlightbackground=self.lightgray,
                               command=self.dataOpen)

        self.butRasterFolder = Button(self.root)
        self.butRasterFolder.place(in_=self.root, x=5, y=35)
        self.butRasterFolder.configure(height=1,
                                       width=10,
                                       text="Raster Folder",
                                       font=self.normaltext,
                                       highlightbackground=self.lightgray,
                                       command=self.rasterOpen)

        self.butOutFolder = Button(self.root)
        self.butOutFolder.place(in_=self.root, x=5, y=65)
        self.butOutFolder.configure(height=1,
                                    width=10,
                                    text="Out Folder",
                                    font=self.normaltext,
                                    highlightbackground=self.lightgray,
                                    command=self.outOpen)

        self.entData = Entry(self.root)
        self.entData.place(in_=self.root, x=100, y=9)
        self.entData.configure(textvariable="file_data",
                               font=self.normaltext,
                               width=97,
                               background=self.darkgray,
                               relief="flat",
                               highlightbackground=self.lightgray)
        self.entData.insert(0, '')

        self.entOutFolder = Entry(self.root)
        self.entOutFolder.place(in_=self.root, x=100, y=69)
        self.entOutFolder.configure(textvariable="out_dir",
                                    font=self.normaltext,
                                    width=97,
                                    background=self.darkgray,
                                    relief="flat",
                                    highlightbackground=self.lightgray)
        self.entOutFolder.insert(0, '')

        self.entRasterFolder = Entry(self.root)
        self.entRasterFolder.place(in_=self.root, x=100, y=39)
        self.entRasterFolder.configure(textvariable="dir_rasters",
                                       font=self.normaltext,
                                       width=97,
                                       background=self.darkgray,
                                       relief="flat",
                                       highlightbackground=self.lightgray)
        self.entRasterFolder.insert(0, '')

        self.activeMethod = StringVar(self.root)
        self.activeMethod.set("Random repetition")
        self.butMETHOD = OptionMenu(
            self.root,
            self.activeMethod,
            "Random repetition",
            "Cross validation",
            "Bootstrapping",
            command=lambda x: self.displayMethodFrame(x))
        self.butMETHOD.place(in_=self.root,
                             x=4,
                             y=97,
                             height="25",
                             width="120")
        self.butMETHOD.configure(font=self.smalltext,
                                 background=self.lightgray)
        self.displayMethodFrame(self.activeMethod.get())

        self.activeOption = StringVar(self.root)
        self.activeOption.set("Network structure")
        self.butOPTION = OptionMenu(
            self.root,
            self.activeOption,
            "Network structure",
            "Options",
            command=lambda x: self.displayOptionFrame(x))
        self.butOPTION.place(in_=self.root,
                             x=4,
                             y=182,
                             height="25",
                             width="120")
        self.butOPTION.configure(font=self.smalltext,
                                 background=self.lightgray)
        self.displayOptionFrame(self.activeOption.get())

        self.Progress_frame = Frame(self.root)
        self.Progress_frame.place(in_=self.root, x=5, y=423)
        self.Progress_frame.configure(borderwidth="2",
                                      relief='sunken',
                                      height="20",
                                      width="105",
                                      bg='white')

        self.Progress_bar = Label(self.Progress_frame)
        self.Progress_bar.place(x=0, y=0)
        self.Progress_bar.configure(font=self.smalltext)

        self.Progress_info = Label(self.root)
        self.Progress_info.place(x=110, y=425)
        self.Progress_info.configure(font=self.smalltext, bg=self.lightgray)

        self.frameButtons = Frame(self.root)
        self.frameButtons.place(in_=self.root, x=5, y=336)
        self.frameButtons.configure(borderwidth="2",
                                    bg=self.lightgray,
                                    relief="raise",
                                    height="84",
                                    width="260")

        self.butREAD = Button(self.root)
        self.butREAD.place(in_=self.frameButtons, x=5, y=5, width=70)
        self.butREAD.configure(font=self.bigtext,
                               highlightbackground=self.lightgray,
                               text="READ",
                               command=self.read)

        self.butRUN = Button(self.root)
        self.butRUN.place(in_=self.frameButtons, x=80, y=5, width=70)
        self.butRUN.configure(font=self.bigtext,
                              highlightbackground=self.lightgray,
                              text="RUN",
                              command=self.returnVar,
                              state='disabled')

        self.butRESULTS = Button(self.root)
        self.butRESULTS.place(in_=self.frameButtons, x=155, y=5, width=80)
        self.butRESULTS.configure(font=self.bigtext,
                                  highlightbackground=self.lightgray,
                                  text="RESULTS",
                                  command=self.returnResults,
                                  state='disabled')

        self.butPROJECT = Button(self.root)
        self.butPROJECT.place(in_=self.frameButtons, x=5, y=45, width=70)
        self.butPROJECT.configure(font=self.boldtext,
                                  highlightbackground=self.lightgray,
                                  text="PROJECT",
                                  command=self.project,
                                  state='disabled')

        self.frameText = Frame(self.root)
        self.frameText.place(in_=self.root, x=270, y=100)
        self.frameText.configure(height=320, width=400)

        self.scrollbar = Scrollbar(self.root)

        self.textFrame = Text(self.frameText, wrap='word')
        self.textFrame.configure(font=self.normaltext, height="24", width="65")
        self.textFrame.place(x=0, y=0)
        self.textFrame.configure(yscrollcommand=self.scrollbar.set)

        self.scrollbar.configure(command=self.textFrame.yview,
                                 highlightbackground=self.lightgray)
        self.scrollbar.place(x=675, y=100, height=320)

    def displayMethodFrame(self, method):
        ''' Displays individual frames for the subsetting method'''
        from Tkinter import Button, Entry, Frame, Label

        if self.__dict__.has_key('frameMethodSelection'):
            self.frameMethodSelection.destroy()

        self.varupdate()
        c = self.conn.simargs

        self.frameMethodSelection = Frame(self.root)
        self.frameMethodSelection.place(in_=self.root, x=5, y=122)
        self.frameMethodSelection.configure(borderwidth="2",
                                            relief="raise",
                                            height="60",
                                            width="260",
                                            bg=self.lightgray)

        if method == "Random repetition":
            self.labRepetitions = Label(self.root)
            self.labRepetitions.place(in_=self.frameMethodSelection, x=2, y=10)
            self.labRepetitions.configure(font=self.normaltext,
                                          borderwidth="1",
                                          justify='left',
                                          anchor='e',
                                          bg=self.lightgray,
                                          text="Number of repetitions:")

            self.entRepetitions = Entry(self.root)
            self.entRepetitions.place(in_=self.frameMethodSelection,
                                      x=125,
                                      y=10)
            self.entRepetitions.configure(textvariable="repetitions",
                                          width="7",
                                          font=self.normaltext,
                                          highlightbackground=self.lightgray)
            self.entRepetitions.delete(0, 'end')
            self.entRepetitions.insert('end', c['repetitions'])

        elif method == "Cross validation":
            self.labRepetitions = Label(self.root)
            self.labRepetitions.place(in_=self.frameMethodSelection, x=2, y=10)
            self.labRepetitions.configure(font=self.normaltext,
                                          bg=self.lightgray,
                                          text="Number of folds:")

            self.entRepetitions = Entry(self.root)
            self.entRepetitions.place(in_=self.frameMethodSelection,
                                      x=100,
                                      y=10)
            self.entRepetitions.configure(textvariable="repetitions",
                                          width="7",
                                          highlightbackground=self.lightgray,
                                          font=self.normaltext)
            self.entRepetitions.delete(0, 'end')
            self.entRepetitions.insert('end', c['repetitions'])

        elif method == "Bootstrapping":
            self.labRepetition = Label(self.root)
            self.labRepetition.place(in_=self.frameMethodSelection, x=2, y=5)
            self.labRepetition.configure(borderwidth="1",
                                         text="Number of Bootstraps:",
                                         bg=self.lightgray,
                                         font=self.normaltext)

            self.entRepetitions = Entry(self.root)
            self.entRepetitions.place(in_=self.frameMethodSelection,
                                      x=125,
                                      y=5)
            self.entRepetitions.configure(textvariable="repetitions",
                                          width="7",
                                          highlightbackground=self.lightgray,
                                          font=self.normaltext)
            self.entRepetitions.delete(0, 'end')
            self.entRepetitions.insert('end', c['repetitions'])

            self.labBsize = Label(self.root)
            self.labBsize.place(in_=self.frameMethodSelection, x=2, y=30)
            self.labBsize.configure(borderwidth="1",
                                    text="Bootstraps Sample Size:",
                                    bg=self.lightgray,
                                    font=self.normaltext)

            self.entBsize = Entry(self.root)
            self.entBsize.place(in_=self.frameMethodSelection, x=125, y=30)
            self.entBsize.configure(textvariable="Bsize",
                                    width="7",
                                    highlightbackground=self.lightgray,
                                    font=self.normaltext)
            self.entBsize.delete(0, 'end')
            self.entBsize.insert('end', c['bsize'])

    def displayOptionFrame(self, option):
        ''' Displays individual frames for the subsetting method'''
        from Tkinter import Button, Entry, Frame, Label, Checkbutton

        if self.__dict__.has_key('frameOptionSelection'):
            self.frameOptionSelection.destroy()

        self.varupdate()
        c = self.conn.simargs

        self.frameOptionSelection = Frame(self.root)
        self.frameOptionSelection.place(in_=self.root, x=5, y=207)
        self.frameOptionSelection.configure(borderwidth="2",
                                            relief="raise",
                                            height="125",
                                            width="260",
                                            bg=self.lightgray)

        if option == "Network structure":
            self.labMaxiter = Label(self.root)
            self.labMaxiter.place(in_=self.frameOptionSelection, x=190, y=5)
            self.labMaxiter.configure(borderwidth="1",
                                      font=self.normaltext,
                                      text="Internal",
                                      bg=self.lightgray)

            self.labNNN = Label(self.root)
            self.labNNN.place(in_=self.frameOptionSelection, x=95, y=5)
            self.labNNN.configure(borderwidth="1",
                                  font=self.normaltext,
                                  text="Reported",
                                  bg=self.lightgray)

            self.labTI = Label(self.root)
            self.labTI.place(in_=self.frameOptionSelection, x=5, y=25)
            self.labTI.configure(borderwidth="1",
                                 font=self.normaltext,
                                 text="Total iterations =",
                                 bg=self.lightgray)

            self.entITERReport = Entry(self.root)
            self.entITERReport.place(in_=self.frameOptionSelection, x=88, y=25)
            self.entITERReport.configure(textvariable="AUCReport",
                                         width="10",
                                         font=self.normaltext,
                                         highlightbackground=self.lightgray)
            self.entITERReport.delete(0, 'end')
            self.entITERReport.insert('end', c['iterreport'])

            self.times = Label(self.root)
            self.times.place(in_=self.frameOptionSelection, x=160, y=25)
            self.times.configure(text="x",
                                 font=self.normaltext,
                                 bg=self.lightgray)

            self.entITERInter = Entry(self.root)
            self.entITERInter.place(in_=self.frameOptionSelection, x=180, y=25)
            self.entITERInter.configure(textvariable="maxiter",
                                        width="10",
                                        font=self.normaltext,
                                        highlightbackground=self.lightgray)
            self.entITERInter.delete(0, 'end')
            self.entITERInter.insert('end', c['iterinter'])

            self.labEta = Label(self.root)
            self.labEta.place(in_=self.frameOptionSelection, x=5, y=55)
            self.labEta.configure(borderwidth="1",
                                  font=self.normaltext,
                                  text="Learning Rate",
                                  bg=self.lightgray)

            self.butHINT = Button(self.root)
            self.butHINT.place(in_=self.frameOptionSelection,
                               x=65,
                               y=75,
                               height=23,
                               width=20)
            self.butHINT.configure(font=self.smalltext,
                                   text="H",
                                   command=self.hint,
                                   state='disabled',
                                   highlightbackground=self.lightgray)

            self.labMomentum = Label(self.root)
            self.labMomentum.place(in_=self.frameOptionSelection, x=88, y=55)
            self.labMomentum.configure(borderwidth="1",
                                       font=self.normaltext,
                                       text="Momentum",
                                       bg=self.lightgray)

            self.entLRATE = Entry(self.root)
            self.entLRATE.place(in_=self.frameOptionSelection, x=5, y=75)
            self.entLRATE.configure(textvariable="eta",
                                    width="8",
                                    font=self.normaltext,
                                    highlightbackground=self.lightgray)
            self.entLRATE.delete(0, 'end')
            self.entLRATE.insert('end', c['lrate'])

            self.entMomentum = Entry(self.root)
            self.entMomentum.place(in_=self.frameOptionSelection, x=90, y=75)
            self.entMomentum.configure(textvariable="momentum",
                                       width="8",
                                       font=self.normaltext,
                                       highlightbackground=self.lightgray)
            self.entMomentum.delete(0, 'end')
            self.entMomentum.insert('end', c['momentum'])

            self.labNNS = Label(self.root)
            self.labNNS.place(in_=self.frameOptionSelection, x=165, y=55)
            self.labNNS.configure(borderwidth="1",
                                  font=self.normaltext,
                                  text="Hidden Layers",
                                  bg=self.lightgray)

            self.entNNShape = Entry(self.root)
            self.entNNShape.place(in_=self.frameOptionSelection, x=160, y=75)
            self.entNNShape.configure(textvariable="HiddenLyr",
                                      width="14",
                                      font=self.normaltext,
                                      highlightbackground=self.lightgray)
            self.entNNShape.delete(0, 'end')
            self.entNNShape.insert('end', c['hiddenlyrs'])

        elif option == "Options":

            self.labPercentage = Label(self.root)
            self.labPercentage.place(in_=self.frameOptionSelection, x=2, y=5)
            self.labPercentage.configure(borderwidth="1",
                                         text="Test %:",
                                         font=self.normaltext,
                                         bg=self.lightgray)

            self.entPercentage = Entry(self.root)
            self.entPercentage.place(in_=self.frameOptionSelection,
                                     x=45,
                                     y=5,
                                     width=30)
            self.entPercentage.configure(textvariable="Percentage",
                                         font=self.normaltext,
                                         highlightbackground=self.lightgray)
            self.entPercentage.delete(0, 'end')
            self.entPercentage.insert('end', c['percentage'])

            self.labAPRatio = Label(self.root)
            self.labAPRatio.place(in_=self.frameOptionSelection, x=80, y=5)
            self.labAPRatio.configure(borderwidth="1",
                                      text="Pseudoabsences/Presences:",
                                      font=self.normaltext,
                                      bg=self.lightgray)

            self.entAPRatio = Entry(self.root)
            self.entAPRatio.place(in_=self.frameOptionSelection, x=220, y=5)
            self.entAPRatio.configure(textvariable="apratio",
                                      width="4",
                                      font=self.normaltext,
                                      highlightbackground=self.lightgray)
            self.entAPRatio.delete(0, 'end')
            self.entAPRatio.insert('end', c['apratio'])

            self.labBurnin = Label(self.root)
            self.labBurnin.place(in_=self.frameOptionSelection, x=2, y=30)
            self.labBurnin.configure(borderwidth="1",
                                     text="Burn-in iterations:",
                                     font=self.normaltext,
                                     bg=self.lightgray)

            self.entBurnin = Entry(self.root)
            self.entBurnin.place(in_=self.frameOptionSelection, x=90, y=30)
            self.entBurnin.configure(textvariable="burnin",
                                     width="8",
                                     font=self.normaltext,
                                     highlightbackground=self.lightgray)
            self.entBurnin.delete(0, 'end')
            self.entBurnin.insert('end', c['burnin'])

            self.chkAucFilter = Checkbutton(self.root)
            self.chkAucFilter.place(in_=self.frameOptionSelection, x=2, y=60)
            self.chkAucFilter.configure(font=self.normaltext,
                                        text="Filter with AUC threshold",
                                        variable=self.aucfilter,
                                        bg=self.lightgray,
                                        command=self.aucstate)

            self.labAUCTrain = Label(self.root)
            self.labAUCTrain.place(in_=self.frameOptionSelection, x=5, y=85)
            self.labAUCTrain.configure(borderwidth="1",
                                       font=self.normaltext,
                                       text="training data",
                                       bg=self.lightgray)

            self.entAUCTrain = Entry(self.root)
            self.entAUCTrain.place(in_=self.frameOptionSelection, x=70, y=85)
            self.entAUCTrain.configure(textvariable="valueAuc",
                                       width="8",
                                       font=self.normaltext,
                                       highlightbackground=self.lightgray)
            self.entAUCTrain.delete(0, 'end')
            self.entAUCTrain.insert('end', c['auctrain'])

            self.labAUCTest = Label(self.root)
            self.labAUCTest.place(in_=self.frameOptionSelection, x=130, y=85)
            self.labAUCTest.configure(borderwidth="1",
                                      font=self.normaltext,
                                      text="testing data",
                                      bg=self.lightgray)

            self.entAUCTest = Entry(self.root)
            self.entAUCTest.place(in_=self.frameOptionSelection, x=195, y=85)
            self.entAUCTest.configure(textvariable="valueAucTest",
                                      width="8",
                                      font=self.normaltext,
                                      highlightbackground=self.lightgray)
            self.entAUCTest.delete(0, 'end')
            self.entAUCTest.insert('end', c['auctest'])

            self.aucstate()

    def varupdate(self):
        extract = self.extract
        c = self.conn.simargs

        c['file_data'] = extract('entData', c['file_data'])
        c['dir_rasters'] = extract('entRasterFolder', c['dir_rasters'])
        c['out_dir'] = extract('entOutFolder', c['out_dir'])
        c['method'] = extract('activeMethod', c['method'])
        c['iterreport'] = int(extract('entITERReport', c['iterreport']))
        c['iterinter'] = int(extract('entITERInter', c['iterinter']))
        c['lrate'] = float(extract('entLRATE', c['lrate']))
        c['momentum'] = float(extract('entMomentum', c['momentum']))
        c['hiddenlyrs'] = extract('entNNShape', c['hiddenlyrs'])
        c['apratio'] = float(extract('entAPRatio', c['apratio']))
        c['percentage'] = int(extract('entPercentage', c['percentage']))
        c['burnin'] = int(extract('entBurnin', c['burnin']))
        c['auctrain'] = float(extract('entAUCTrain', c['auctrain']))
        c['auctest'] = float(extract('entAUCTest', c['auctest']))
        c['repetitions'] = int(extract('entRepetitions', c['repetitions']))
        c['bsize'] = int(extract('entBsize', c['bsize']))
        c['aucfilter'] = bool(extract('aucfilter', int(c['aucfilter'])))

    def extract(self, test, default):
        if test in self.__dict__.keys():
            value = self.__dict__[test].get()
        else:
            value = default
        return value

    def read(self):
        import time
        self.varupdate()
        self.conn.processor(self.conn.manager.read_all, 'read')

    def returnVar(self):
        # Updates variables
        self.varupdate()
        self.conn.processor(self.conn.manager.model, 'run')

    def returnResults(self):
        self.varupdate()
        self.conn.processor(self.conn.manager.results, 'results')

    def project(self):
        self.varupdate()
        project_dir = askdirectory()
        self.conn.simargs['project_dir'] = project_dir
        self.conn.processor(self.conn.manager.project, 'project')

    def hint(self):
        self.varupdate()
        self.conn.processor(self.conn.manager.hint, 'hint')

    def dataOpen(self):
        self.entData.delete(0, 'end')
        file_data = askopenfilename(filetypes=[("text files",
                                                "*.txt"), ("allfiles", "*")])
        self.entData.insert('end', file_data)

    def rasterOpen(self):
        self.entRasterFolder.delete(0, 'end')
        dir_rasters = askdirectory()
        self.entRasterFolder.insert('end', dir_rasters)

    def outOpen(self):
        self.entOutFolder.delete(0, 'end')
        out_dir = askdirectory()
        self.entOutFolder.insert('end', out_dir)

    def update_text(self, string_txt):
        txt = string_txt + " \n"
        self.textFrame.insert('end', txt)
        self.textFrame.yview('end')

    def processGraph(self, graph_object):
        '''Just a wraper to call the graphics creation object'''
        graph_object()

    def periodicUpdate(self):
        """Executes periodic checks to GUI:
            - if there are new messages and displays when true"""
        try:
            while 1:
                code, args, kwargs = self.queue.get_nowait()
                if code == Connector.CODE_TEXT:
                    self.update_text(*args)
                elif code == Connector.CODE_PROGRESS:
                    self.progress(*args, **kwargs)
                elif code == Connector.CODE_MODIFY_BUTTON:
                    self.modify_but(*args)
                elif code == Connector.CODE_SHOWRESULTS:
                    self.showResults(*args)
                elif code == Connector.CODE_GRAPHS:
                    self.processGraph(args)
                else:
                    self.update_text('Unknown message...')
                self.queue.task_done()
                self.root.update()
        except Queue.Empty:
            pass
        self.root.after(100, self.periodicUpdate)

    def modify_but(self, state, buttonlist):
        if buttonlist == 'all':
            buttonlist = [
                'READ', 'RUN', 'RESULTS', 'PROJECT', 'HINT', 'METHOD', 'OPTION'
            ]
        for button in buttonlist:
            but = "self.but%s.configure(state=\'%s\')" % (button, state)
            exec(but)

    def abundance(self):
        self.entAUCTrain.configure(state='disabled')
        self.entAUCTest.configure(state='disabled')

    def aucstate(self):
        if self.aucfilter.get(): state = 'normal'
        else: state = 'disabled'
        self.entAUCTrain.configure(state=state)
        self.entAUCTest.configure(state=state)

    def progress(self, value, maxvalue, **kwargs):
        '''Shows the progress bar in GUI
           args are:
            Value    - Value of the current progress
            MaxValue - Value where progress terminates
           kwargs are
            color    - Color for the progess bar
            msg      - message to display'''
        color = 'blue'
        if 'color' in kwargs: color = kwargs['color']
        percent = (value * 100) / maxvalue
        self.Progress_bar.configure(font=self.smalltext,
                                    foreground="white",
                                    background=color)  #"#0000ff"
        if percent <> 100:
            width = int((percent / 100.000) * 20)
            text = '%s%%' % percent
            self.Progress_bar.configure(text=text, width=width)
            if 'msg' in kwargs:
                self.Progress_info.configure(text=kwargs['msg'])
        elif percent == 100:
            self.Progress_bar.configure(text="",
                                        width=0,
                                        relief="flat",
                                        background="#ece9d8")
            self.Progress_info.configure(text="")

    def showResults(self, figures):
        from Tkinter import Button
        figures = [self.entOutFolder.get() + "/" + x for x in figures]
        ResultsWindow = mytoplevel(self.root, figures, self)
        ResultsWindow.title('Results')
        butRW = Button(ResultsWindow,
                       text='CLOSE',
                       command=ResultsWindow.destroy)
        butRW.pack()

    def update_queue(self):
        try:
            while self.queue.qsize():
                msg = '%s\n' % self.queue.get(0)
                self.textFrame.insert('end', msg)
                self.textFrame.yview('end')
        except Queue.Empty:
            pass
Example #29
0
class GUI(Tk):

    def __init__(self, parent):
        '''Constructor'''
        Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()


    def initialize(self):
        '''Sets the parameters of the view and displays it'''
        self.grid()
        self.fullscreen()
        self.update()


    def fullscreen(self):
        '''Sets the view to fullscreen'''
        self.geometry("%dx%d+0+0" % (self.winfo_screenwidth(),
                                     self.winfo_screenheight()))
        self.overrideredirect(1) # Removes borders
        self.resizable(False, False)
        self.configure(background = "black")
        self.focus_set()


    def createPrompt(self, startFunction, endFunction):
        ''' Writes instructions for the participant and keybinds starting
            and ending functions

            Args:
                startFunction(): the function that iterates when the user
                    presses <<ENTER>>
                endFunction(): the function that closes the program and saves
                    the session data upon pressing <<ESCAPE>>
        '''
        self.labelVariable = StringVar()
        self.label = Label(self, textvariable=self.labelVariable,
                      anchor="center", fg="white", bg="black",
                      font="Arial 24 bold", wraplength=1100)
        self.label.grid(column=0, row=0, padx=20, pady=20)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.setLabel(self.loadIntro(), startFunction)
        self.bind("<Escape>", endFunction)


    def createEntryBox(self):
        '''Creates an area for the participant to enter a response'''
        self.entryVariable = StringVar()
        self.entry = Entry(self, textvariable=self.entryVariable,
                           font="Arial 24", bd = 0, fg="white", bg="black",
                           insertbackground = "white", justify = "center")
        self.entry.grid(column=0, row=1, sticky = 'EW')
        self.grid_rowconfigure(0, weight=0)
        self.grid_rowconfigure(1, weight=0)
        self.entry.focus_set()
        self.entryVariable.set("")


    def loadIntro(self):
        '''Loads text from INTRO.txt'''
        currentPath = os.path.dirname(os.path.realpath(__file__))
        file = open(currentPath + "\..\intro.txt")
        intro = file.readlines()
        intro += "\n\nWhen you are ready, press ENTER to continue."
        file.close()

        return ''.join(intro)


    def setLabel(self, message, newFunction):
        '''Changes the text that is displayed on screen

        Args:
            message (str): The text to be displayed
            newFunction(): Executes when the user presses <<ENTER>>
        '''
        self.labelVariable.set(message)
        self.bind("<Return>", newFunction)


    def greyScreen(self):
        '''Displays a grey screen between trials to give the participant a
            short break. Purely aesthetic.
        '''
        GREY = "#888888"
        self.configure(background=GREY)
        self.label.configure(fg=GREY, bg=GREY)
        self.entry.configure(fg=GREY, bg=GREY, insertbackground=GREY)
        self.update()
        sleep(1.5)
        self.configure(background="black")
        self.label.configure(fg="white", bg="black")
        self.entry.configure(fg="white", bg="black", insertbackground="white")
        self.update()
Example #30
0
                     sticky=W + E + N + S)
comPortEntry = Entry(root, bd=4, fg='blue', font=('times', 10), width=7)
comPortEntry.grid(row=12,
                  column=16,
                  rowspan=2,
                  columnspan=1,
                  sticky=W + E + N + S)
for port_no, description, _ in list(serial.tools.list_ports.comports()):
    if (BOARD_COM_STR_DAPLINK
            in description) or (BOARD_COM_STR_MBED
                                in description) or (BOARD_COM_STR_BLUETOOTH
                                                    in description):
        LogToTextBox("Detected Board @ %s..." % port_no)
        comPortEntry.insert(0, port_no)
if not comPortEntry.get():
    comPortEntry.configure(fg='red')
    comPortEntry.insert(0, 'NONE')
goButton = Button(root,
                  bd=4,
                  font=('times', 12, 'bold'),
                  text="CONNECT",
                  bg='greenyellow',
                  command=ConnectIoTAdapter)
goButton.grid(row=12, column=17, rowspan=2, columnspan=1, sticky=W + E + N + S)

Button(root, state=DISABLED, text=COPYRIGHT_STR).grid(row=14,
                                                      column=0,
                                                      rowspan=1,
                                                      columnspan=18,
                                                      sticky=W + E + N + S)
Example #31
0
class editPool(Frame):

    font_decorations = ("italic", "bold", "subscript", "superscript")
    font_decorations_to_names = {
        "italic": _("italic"),
        "bold": _("bold"),
        "subscript": _("subscript"),
        "superscript": _("superscript"),
    }
    font_decorations_to_html = {"italic": "i", "bold": "b", "subscript": "sub", "superscript": "sup"}

    def __init__(self, master, buttons=("interpret", "asis"), **kw):
        Frame.__init__(self, master, **kw)
        self.text = ""
        self.interpret = 1
        self.editPool = Entry(self, width=50, state="disabled", font="Helvetica 12")
        self.editPool.pack(side="left")

        self.editPool.bind("<Return>", self._interpretButtonPressed)
        self.editPool.bind("<Escape>", self._cancel)

        self.editPool.bind("<Control-s>", lambda e: self._tag_it("sub"))
        self.editPool.bind("<Control-S>", lambda e: self._tag_it("sup"))
        self.editPool.bind("<Control-i>", lambda e: self._tag_it("i"))
        self.editPool.bind("<Control-b>", lambda e: self._tag_it("b"))

        self.editPool.bind("<KeyPress>", self._key)

        if "interpret" in buttons:
            pix = Store.app.request("pixmap", name="interpret")
            self.interpretButton = Button(
                self,
                text=_("Interpret"),
                image=pix,
                command=self._interpretButtonPressed,
                state="disabled",
                bd=config.border_width,
            )
            Store.app.balloon.bind(self.interpretButton, _("Interpret text (where applicable)"))
            self.interpretButton.pack(side="left")
        else:
            self.interpretButton = None

        if "asis" in buttons:
            pix = Store.app.request("pixmap", name="asis")
            self.setButton = Button(
                self,
                image=pix,
                text=_("As is"),
                command=self._setButtonPressed,
                state="disabled",
                bd=config.border_width,
            )
            Store.app.balloon.bind(self.setButton, _("Leave text as is - do not interpret"))
            self.setButton.pack(side="left")
        else:
            self.setButton = None

        pix = Store.app.request("pixmap", name="subnum")
        self.numbersToSubButton = Button(
            self,
            image=pix,
            text=_("Sub numbers"),
            command=self._numbersToSubButtonPressed,
            state="disabled",
            bd=config.border_width,
        )
        Store.app.balloon.bind(self.numbersToSubButton, _("Convert numbers to subscript"))
        self.numbersToSubButton.pack(side="left")

        # text decoration
        decorFrame = Frame(self)
        decorFrame.pack(padx=5, side="left")
        for i in self.font_decorations:
            pix = Store.app.request("pixmap", name=i)
            self.__dict__[i] = Button(
                self,
                image=pix,
                command=misc.lazy_apply(self._tag_it, (self.font_decorations_to_html[i],)),
                state="disabled",
                text=self.font_decorations_to_names[i],
                bd=config.border_width,
            )
            Store.app.balloon.bind(self.__dict__[i], self.font_decorations_to_names[i])
            self.__dict__[i].pack(side="left")

        # special characters
        pix = Store.app.request("pixmap", name="specialchar")
        self.specialCharButton = Button(
            self,
            image=pix,
            text=_("Special Character"),
            command=self._specialCharButtonPressed,
            state="disabled",
            bd=config.border_width,
        )
        Store.app.balloon.bind(self.specialCharButton, _("Insert a special character"))
        self.specialCharButton.pack(side="left")
        self.active = False

    def _interpretButtonPressed(self, *e):
        t = self.editPool.get()
        if string.lower(t) in groups_table:
            self._setText(t)
            # self._setText( groups_table[ string.lower(t)]['text'])
            # self.editPool.insert(0, self.text)
        else:
            self._setText(t)
            self.text = re.sub("\\\\n", "\n", self.text)
        self._quit()

    def _setButtonPressed(self, *e):
        self._setText(self.editPool.get())
        self.interpret = 0
        self._quit()

    def _numbersToSubButtonPressed(self, *e):
        self._setText(re.sub("\d+", "<sub>\g<0></sub>", self.editPool.get()))
        self._quit()

    def _cancel(self, e):
        self._setText(None)
        self.active = False
        self._quit()

    def _quit(self):
        self.grab_release()
        self._disable()
        self._normaly_terminated = 1
        self.active = False
        self.quit()

    def _disable(self):
        self.interpretButton.configure(state="disabled")
        self.numbersToSubButton.configure(state="disabled")
        self.setButton.configure(state="disabled")
        self.editPool.configure(state="disabled")
        self.italic.configure(state="disabled")
        self.bold.configure(state="disabled")
        self.superscript.configure(state="disabled")
        self.subscript.configure(state="disabled")
        self.specialCharButton.configure(state="disabled")

    def _enable(self):
        self.interpretButton.configure(state="normal")
        self.numbersToSubButton.configure(state="normal")
        self.setButton.configure(state="normal")
        self.editPool.configure(state="normal")
        self.italic.configure(state="normal")
        self.bold.configure(state="normal")
        self.superscript.configure(state="normal")
        self.subscript.configure(state="normal")
        self.specialCharButton.configure(state="normal")

    def _setText(self, text):
        self.text = text
        self._update()

    def _update(self):
        self.editPool.delete(0, last="end")
        if self.text:
            self.editPool.insert(0, self.text)

    def activate(self, text=None, select=1):
        """activates edit_pool and returns inserted value (None if cancel occured),
    if parameter text is None it preserves the old one, use text='' to delete old text"""
        self.active = True
        self.interpret = 1
        self.focus_set()
        self.grab_set()
        self._enable()
        # this is because I need to distinguish whether the mainloop was terminated "from inside"
        # or from outside (this most of the time means the application was killed and the widgets are no longer available)
        self._normaly_terminated = 0
        if text != None:
            self._setText(text)
        self.editPool.focus_set()
        if select:
            self.editPool.selection_range(0, "end")
        self.mainloop()
        if self._normaly_terminated:
            return self.text
        else:
            return None

    def _tag_it(self, tag):
        if self.editPool.selection_present():
            self.editPool.insert(Tkinter.SEL_FIRST, "<%s>" % tag)
            self.editPool.insert(Tkinter.SEL_LAST, "</%s>" % tag)
        else:
            self.editPool.insert(Tkinter.INSERT, "<%s></%s>" % (tag, tag))
            self.editPool.icursor(self.editPool.index(Tkinter.INSERT) - len(tag) - 3)

    def _key(self, event):
        if len(event.keysym) > 1 and event.keysym in keysyms:
            if self.editPool.selection_present():
                self.editPool.delete("anchor", "insert")
            self.editPool.insert("insert", unicode(keysyms[event.keysym]))
            return "break"

    def _specialCharButtonPressed(self):
        dialog = special_character_menu(self._insertText)
        dialog.post(self.specialCharButton.winfo_rootx(), self.specialCharButton.winfo_rooty())

    def _insertText(self, text):
        if text != None:
            self.editPool.insert(Tkinter.INSERT, text)
        self.grab_set()
Example #32
0
class SearchBox(Frame):
    def __init__(self,
                 master,
                 entry_width=30,
                 entry_font=None,
                 entry_background="white",
                 entry_highlightthickness=1,
                 button_text="Search",
                 button_ipadx=10,
                 button_background="#009688",
                 button_foreground="white",
                 button_font=None,
                 opacity=0.8,
                 placeholder=None,
                 placeholder_font=None,
                 placeholder_color="grey",
                 spacing=3,
                 command=None):
        Frame.__init__(self, master)

        self._command = command

        self.entry = Entry(self,
                           width=entry_width,
                           background=entry_background,
                           highlightcolor=button_background,
                           highlightthickness=entry_highlightthickness)
        self.entry.pack(side=LEFT, fill=BOTH, ipady=1, padx=(0, spacing))

        if entry_font:
            self.entry.configure(font=entry_font)

        if placeholder:
            add_placeholder_to(self.entry,
                               placeholder,
                               color=placeholder_color,
                               font=placeholder_font)

        self.entry.bind("<Escape>",
                        lambda event: self.entry.nametowidget(".").focus())
        self.entry.bind("<Return>", self._on_execute_command)

        opacity = float(opacity)

        if button_background.startswith("#"):
            r, g, b = hex2rgb(button_background)
        else:
            # Color name
            r, g, b = master.winfo_rgb(button_background)

        r = int(opacity * r)
        g = int(opacity * g)
        b = int(opacity * b)

        if r <= 255 and g <= 255 and b <= 255:
            self._button_activebackground = '#%02x%02x%02x' % (r, g, b)
        else:
            self._button_activebackground = '#%04x%04x%04x' % (r, g, b)

        self._button_background = button_background

        self.button_label = Label(self,
                                  text=button_text,
                                  background=button_background,
                                  foreground=button_foreground,
                                  font=button_font)
        if entry_font:
            self.button_label.configure(font=button_font)

        self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx)

        self.button_label.bind("<Enter>", self._state_active)
        self.button_label.bind("<Leave>", self._state_normal)

        self.button_label.bind("<ButtonRelease-1>", self._on_execute_command)

    def get_text(self):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            if entry.placeholder_state.contains_placeholder:
                return ""
            else:
                return entry.get()
        else:
            return entry.get()

    def set_text(self, text):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            entry.placeholder_state.contains_placeholder = False

        entry.delete(0, END)
        entry.insert(0, text)

    def clear(self):
        self.entry_var.set("")

    def focus(self):
        self.entry.focus()

    def _on_execute_command(self, event):
        text = self.get_text()
        self._command(text)

    def _state_normal(self, event):
        self.button_label.configure(background=self._button_background)

    def _state_active(self, event):
        self.button_label.configure(background=self._button_activebackground)
Example #33
0
class _Hatch_GUI(object):
    """
    create a Hatch object from
    hatch_supt and to then create a skeleton python project.
    """
    def __init__(self, master):
        self.initComplete = 0
        self.master = master
        self.x, self.y, self.w, self.h = -1, -1, -1, -1

        # bind master to <Configure> in order to handle any resizing, etc.
        # postpone self.master.bind("<Configure>", self.Master_Configure)
        self.master.bind('<Enter>', self.bindConfigure)

        self.master.title("PyHatch GUI")
        self.master.resizable(0, 0)  # Linux may not respect this

        dialogframe = Frame(master, width=810, height=630)
        dialogframe.pack()

        self.Shortdesc_Labelframe = LabelFrame(
            dialogframe,
            text="Short Description (1-liner)",
            height="90",
            width="718")
        self.Shortdesc_Labelframe.place(x=60, y=127)

        helv20 = tkFont.Font(family='Helvetica', size=20, weight='bold')

        self.Buildproject_Button = Button(dialogframe,
                                          text="Build Project",
                                          width="15",
                                          font=helv20)
        self.Buildproject_Button.place(x=492, y=10, width=263, height=68)
        self.Buildproject_Button.bind("<ButtonRelease-1>",
                                      self.Buildproject_Button_Click)

        self.Selectdir_Button = Button(dialogframe,
                                       text="<Select Directory>",
                                       width="15")
        self.Selectdir_Button.place(x=72, y=585, width=672, height=31)
        self.Selectdir_Button.bind("<ButtonRelease-1>",
                                   self.Selectdir_Button_Click)

        self.Author_Entry = Entry(dialogframe, width="15")
        self.Author_Entry.place(x=228, y=424, width=187, height=21)
        self.Author_Entry_StringVar = StringVar()
        self.Author_Entry.configure(textvariable=self.Author_Entry_StringVar)
        self.Author_Entry_StringVar.set("John Doe")

        self.Classname_Entry = Entry(dialogframe, width="15")
        self.Classname_Entry.place(x=192, y=73, width=165, height=21)
        self.Classname_Entry_StringVar = StringVar()
        self.Classname_Entry.configure(
            textvariable=self.Classname_Entry_StringVar)
        self.Classname_Entry_StringVar.set("MyClass")

        self.Copyright_Entry = Entry(dialogframe, width="15")
        self.Copyright_Entry.place(x=228, y=478, width=461, height=21)
        self.Copyright_Entry_StringVar = StringVar()
        self.Copyright_Entry.configure(
            textvariable=self.Copyright_Entry_StringVar)
        self.Copyright_Entry_StringVar.set("Copyright (c) 2013 John Doe")

        self.Email_Entry = Entry(dialogframe, relief="sunken", width="15")
        self.Email_Entry.place(x=228, y=505, width=458, height=21)
        self.Email_Entry_StringVar = StringVar()
        self.Email_Entry.configure(textvariable=self.Email_Entry_StringVar)
        self.Email_Entry_StringVar.set("*****@*****.**")

        self.GithubUserName_Entry = Entry(dialogframe,
                                          relief="sunken",
                                          width="15")
        self.GithubUserName_Entry.place(x=228, y=539, width=458, height=21)
        self.GithubUserName_Entry_StringVar = StringVar()
        self.GithubUserName_Entry.configure(
            textvariable=self.GithubUserName_Entry_StringVar)
        self.GithubUserName_Entry_StringVar.set("github_user_name")

        self.Funcname_Entry = Entry(dialogframe, width="15")
        self.Funcname_Entry.place(x=192, y=100, width=157, height=21)
        self.Funcname_Entry_StringVar = StringVar()
        self.Funcname_Entry.configure(
            textvariable=self.Funcname_Entry_StringVar)
        self.Funcname_Entry_StringVar.set("my_function")

        # License values should be correct format
        LICENSE_OPTIONS = tuple(sorted(CLASSIFIER_D.keys()))
        self.License_Entry_StringVar = StringVar()
        self.License_Entry = OptionMenu(dialogframe,
                                        self.License_Entry_StringVar,
                                        *LICENSE_OPTIONS)
        self.License_Entry.place(x=552, y=424, width=184, height=21)
        self.License_Entry_StringVar.set(LICENSE_OPTIONS[0])

        self.Mainpyname_Entry = Entry(dialogframe, width="15")
        self.Mainpyname_Entry.place(x=168, y=37, width=196, height=21)
        self.Mainpyname_Entry_StringVar = StringVar()
        self.Mainpyname_Entry.configure(
            textvariable=self.Mainpyname_Entry_StringVar)
        self.Mainpyname_Entry_StringVar.set("main.py")

        self.Projname_Entry = Entry(dialogframe, width="15")
        self.Projname_Entry.place(x=168, y=10, width=194, height=21)
        self.Projname_Entry_StringVar = StringVar()
        self.Projname_Entry.configure(
            textvariable=self.Projname_Entry_StringVar)
        self.Projname_Entry_StringVar.set("MyProject")

        self.Shortdesc_Entry = Entry(dialogframe, width="15")
        self.Shortdesc_Entry.place(x=72, y=150, width=688, height=48)
        self.Shortdesc_Entry_StringVar = StringVar()
        self.Shortdesc_Entry.configure(
            textvariable=self.Shortdesc_Entry_StringVar)
        self.Shortdesc_Entry_StringVar.set("My project does this")

        # Status must be correct format
        self.Status_Entry_StringVar = StringVar()
        self.Status_Entry = OptionMenu(dialogframe,
                                       self.Status_Entry_StringVar,
                                       *DEV_STATUS_OPTIONS)
        self.Status_Entry.place(x=228, y=451, width=183, height=21)
        self.Status_Entry_StringVar.set(DEV_STATUS_OPTIONS[0])

        self.Version_Entry = Entry(dialogframe, width="15")
        self.Version_Entry.place(x=552, y=451, width=184, height=21)
        self.Version_Entry_StringVar = StringVar()
        self.Version_Entry.configure(textvariable=self.Version_Entry_StringVar)
        self.Version_Entry_StringVar.set("0.1.1")

        self.Author_Label = Label(dialogframe, text="Author", width="15")
        self.Author_Label.place(x=96, y=424, width=112, height=22)

        self.Classname_Label = Label(dialogframe,
                                     text="Class Name",
                                     width="15")
        self.Classname_Label.place(x=60, y=73, width=112, height=22)

        self.Copyright_Label = Label(dialogframe, text="Copyright", width="15")
        self.Copyright_Label.place(x=96, y=478, width=113, height=23)

        self.Email_Label = Label(dialogframe, text="Email", width="15")
        self.Email_Label.place(x=96, y=505, width=113, height=23)

        self.GithubUserName_Label = Label(dialogframe,
                                          text="GithubUserName",
                                          width="15")
        self.GithubUserName_Label.place(x=96, y=539, width=113, height=23)

        self.Funcname_Label = Label(dialogframe,
                                    text="Function Name",
                                    width="15")
        self.Funcname_Label.place(x=60, y=100, width=112, height=22)

        self.License_Label = Label(dialogframe, text="License", width="15")
        self.License_Label.place(x=432, y=424, width=113, height=23)

        self.Longdesc_Label = Label(dialogframe,
                                    text="Paragraph Description",
                                    width="15")
        self.Longdesc_Label.place(x=216, y=220, width=376, height=22)

        self.Mainpyname_Label = Label(dialogframe,
                                      text="Main Python File",
                                      width="15")
        self.Mainpyname_Label.place(x=48, y=37, width=112, height=22)

        self.Projname_Label = Label(dialogframe,
                                    text="Project Name",
                                    width="15")
        self.Projname_Label.place(x=48, y=10, width=112, height=22)

        self.Selectdir_Label = Label(
            dialogframe,
            text="Select the Directory Below Which to Place Your Project",
            width="15")
        self.Selectdir_Label.place(x=156, y=567, width=536, height=24)

        self.Status_Label = Label(dialogframe, text="Status", width="15")
        self.Status_Label.place(x=96, y=451, width=114, height=24)

        self.Version_Label = Label(dialogframe, text="Version", width="15")
        self.Version_Label.place(x=432, y=451, width=113, height=23)

        self.Isclass_Radiobutton = Radiobutton(dialogframe,
                                               text="Class Project",
                                               value="Class Project",
                                               width="15",
                                               anchor=W)
        self.Isclass_Radiobutton.place(x=320, y=73, width=135, height=27)
        self.RadioGroup1_StringVar = StringVar()
        self.RadioGroup1_StringVar.set("Class Project")
        self.RadioGroup1_StringVar_traceName = \
            self.RadioGroup1_StringVar.trace_variable("w",
                                                      self.RadioGroup1_StringVar_Callback)
        self.Isclass_Radiobutton.configure(variable=self.RadioGroup1_StringVar)

        self.Isfunction_Radiobutton = Radiobutton(dialogframe,
                                                  text="Function Project",
                                                  value="Function Project",
                                                  width="15",
                                                  anchor=W)
        self.Isfunction_Radiobutton.place(x=320, y=100, width=135, height=27)
        self.Isfunction_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        lbframe = Frame(dialogframe)
        self.Text_1_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Text_1 = Text(lbframe,
                           width="40",
                           height="6",
                           yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Text_1.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Text_1.pack(side=LEFT, fill=BOTH, expand=1)

        self.Text_1_frame.place(x=72, y=250, width=665, height=160)
        # >>>>>>insert any user code below this comment for section "top_of_init"

        self.dirname = '<Select Directory>'
        self.Funcname_Entry.config(state=DISABLED)

        h = Hatch(projName='MyProject', mainDefinesClass='N')
        if h.author:
            self.Author_Entry_StringVar.set(h.author)
        if h.proj_license:
            self.License_Entry_StringVar.set(h.proj_license)
        if h.proj_copyright:
            self.Copyright_Entry_StringVar.set(h.proj_copyright)
        if h.email:
            self.Email_Entry_StringVar.set(h.email)
        if h.github_user_name:
            self.GithubUserName_Entry_StringVar.set(h.github_user_name)
        del h

    def build_result_dict(self):
        """Takes user inputs from GUI and builds a dictionary of results"""
        # pylint: disable=W0201
        self.result = {}  # return a dictionary of results

        self.result["author"] = self.Author_Entry_StringVar.get()
        self.result["status"] = self.Status_Entry_StringVar.get()
        self.result["proj_license"] = self.License_Entry_StringVar.get()
        self.result["version"] = self.Version_Entry_StringVar.get()
        self.result["proj_copyright"] = self.Copyright_Entry_StringVar.get()
        self.result["email"] = self.Email_Entry_StringVar.get()
        self.result[
            "github_user_name"] = self.GithubUserName_Entry_StringVar.get()

        self.result["main_py_name"] = self.Mainpyname_Entry_StringVar.get()
        self.result["proj_name"] = self.Projname_Entry_StringVar.get()
        self.result["class_name"] = self.Classname_Entry_StringVar.get()
        self.result["func_name"] = self.Funcname_Entry_StringVar.get()

        self.result["short_desc"] = self.Shortdesc_Entry_StringVar.get()
        self.result["para_desc"] = self.Text_1.get(1.0, END)
        self.result["parent_dir"] = self.dirname

        if self.RadioGroup1_StringVar.get() == "Class Project":
            self.result["is_class_project"] = 'Y'
        else:
            self.result["is_class_project"] = 'N'

    def Buildproject_Button_Click(self, event):
        """When clicked, this method gathers all the user inputs
            and builds the project skeleton in the directory specified.
        """

        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613

        # >>>>>>insert any user code below this comment for section "compID=29"
        # replace, delete, or comment-out the following
        #print "executed method Buildproject_Button_Click"

        if not os.path.isdir(self.dirname):
            ShowError(
                title='Need Parent Directory',
                message=
                'You need to choose a directory in which to place your project.'
            )
        else:
            self.build_result_dict()  # builds self.result dict
            r = self.result

            h = Hatch(projName=r["proj_name"],
                      mainDefinesClass=r["is_class_project"],
                      mainPyFileName=r["main_py_name"],
                      mainClassName=r["class_name"],
                      mainFunctionName=r["func_name"],
                      author=r["author"],
                      proj_copyright=r["proj_copyright"],
                      proj_license=r["proj_license"],
                      version=r["version"],
                      email=r["email"],
                      status=r["status"],
                      github_user_name=r["github_user_name"],
                      simpleDesc=r["short_desc"],
                      longDesc=r["para_desc"])

            call_result = h.save_project_below_this_dir(self.dirname)
            if call_result == 'Success':
                if AskYesNo(title='Exit Dialog',
                            message='Do you want to leave this GUI?'):
                    self.master.destroy()
            else:
                ShowWarning( title='Project Build Error',
                             message='Project did NOT build properly.\n'+\
                            'Warning Message = (%s)'%call_result)

    # return a string containing directory name
    def AskDirectory(self, title='Choose Directory', initialdir="."):
        """Simply wraps the tkinter function of the "same" name."""
        dirname = tkFileDialog.askdirectory(parent=self.master,
                                            initialdir=initialdir,
                                            title=title)
        return dirname  # <-- string

    def Selectdir_Button_Click(self, event):
        #  I don't care what the exception is, if there's a problem, bail
        #     Also, I want to redefine the dirname attribute here
        # pylint: disable=W0702, W0201

        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        """Selects the directory in which to build project."""

        dirname = self.AskDirectory(title='Choose Directory For Nose Tests',
                                    initialdir='.')
        if dirname:
            try:
                dirname = os.path.abspath(dirname)
            except:
                self.dirname = '<Select Directory>'
                return  # let Alarm force dir selection

            self.dirname = dirname

            self.Selectdir_Button.config(text=self.dirname)

    def RadioGroup1_StringVar_Callback(self, varName, index, mode):
        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        """Responds to changes in RadioGroup1_StringVar."""
        if self.RadioGroup1_StringVar.get() == "Class Project":
            self.Funcname_Entry.config(state=DISABLED)
            self.Classname_Entry.config(state=NORMAL)
        else:
            self.Classname_Entry.config(state=DISABLED)
            self.Funcname_Entry.config(state=NORMAL)

    # tk_happy generated code. DO NOT EDIT THE FOLLOWING. section "Master_Configure"
    def bindConfigure(self, event):
        """bindConfigure and Master_Configure help stabilize GUI"""
        #  tkinter requires arguments, but I don't use them
        # pylint: disable=W0613
        if not self.initComplete:
            self.master.bind("<Configure>", self.Master_Configure)
            self.initComplete = 1

    def Master_Configure(self, event):
        """bindConfigure and Master_Configure help stabilize GUI"""
        # >>>>>>insert any user code below this comment for section "Master_Configure"
        # replace, delete, or comment-out the following
        if event.widget != self.master:
            if self.w != -1:
                return
        x = int(self.master.winfo_x())
        y = int(self.master.winfo_y())
        w = int(self.master.winfo_width())
        h = int(self.master.winfo_height())
        if (self.x, self.y, self.w, self.h) == (-1, -1, -1, -1):
            self.x, self.y, self.w, self.h = x, y, w, h

        if self.w != w or self.h != h:
            print "Master reconfigured... make resize adjustments"
            self.w = w
            self.h = h