def create_widgets(self):
     self.name = StringVar(self.parent)
     self.fontSize = StringVar(self.parent)
     self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
     self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
     self.messageInfo = Message(self.frameMain,
                                anchor=W,
                                justify=LEFT,
                                padx=5,
                                pady=5,
                                text=self.message)  #,aspect=200)
     entryName = Entry(self.frameMain, textvariable=self.name, width=30)
     entryName.focus_set()
     self.messageInfo.pack(padx=5, pady=5)  #, expand=TRUE, fill=BOTH)
     entryName.pack(padx=5, pady=5)
     frameButtons = Frame(self, pady=2)
     frameButtons.pack(side=BOTTOM)
     self.buttonOk = Button(frameButtons,
                            text='Ok',
                            width=8,
                            command=self.Ok)
     self.buttonOk.pack(side=LEFT, padx=5)
     self.buttonCancel = Button(frameButtons,
                                text='Cancel',
                                width=8,
                                command=self.Cancel)
     self.buttonCancel.pack(side=RIGHT, padx=5)
Ejemplo n.º 2
0
 def showLoading(self):
     self.attemptedMarkov = True
     popup = Toplevel()
     text = Message(popup, text="The Markov Generator is still loading!\n\nText will show up when loaded!")
     text.pack()
     closePop = Button(popup, text="Okay!", command=popup.destroy)
     closePop.pack()  
Ejemplo n.º 3
0
 def __init__(self, wdw, sols):
     """
     Stores the list of solutions in sols
     and defines the layout of the GUI.
     """
     wdw.title('solutions scroller')
     self.sols = sols
     self.cursor = 0
     self.lbl = Label(wdw, text="solution : ")
     self.lbl.grid(row=0, column=0, sticky=E)
     self.ent = Entry(wdw)
     self.ent.grid(row=0, column=1, stick=W)
     self.ent.insert(INSERT, "0 of %d" % len(sols))
     self.myft = Font(family="Courier New", size=12, weight="normal")
     self.mlen = self.myft.measure("M")
     lines = sols[0].split('\n')
     self.width = max([len(line) for line in lines])
     self.display = StringVar()
     self.display.set(self.sols[0])
     self.mess = Message(wdw, textvariable=self.display, \
         font=self.myft, width=self.width*self.mlen, background='white')
     self.mess.grid(row=1, column=0, columnspan=2)
     self.btnext = Button(wdw, command=self.next, text='next')
     self.btnext.grid(row=2, column=1, sticky=W + E)
     self.btprev = Button(wdw, command=self.previous, text='previous')
     self.btprev.grid(row=2, column=0, sticky=W + E)
Ejemplo n.º 4
0
        def callback(event):
            event.widget.focus_set()
            print "clicked at", event.x, event.y

            if self.add_tasks_flg.get() == 1:
                # Select number of robots
                # Define elements of pop up window
                self.top = Toplevel()

                self.num_robots = StringVar(self.top)
                self.num_robots.set("1")  # default value
                w = OptionMenu(self.top, self.num_robots, '1', '2', '3',
                               '4').grid(row=0, column=1)
                text1 = Message(self.top, text="Number of robots:",
                                width=150).grid(row=0, column=0)

                self.e = Entry(self.top, width=10)
                self.e.grid(row=1, column=1)
                text2 = Message(self.top, text="Task duration:",
                                width=150).grid(row=1, column=0)
                text3 = Message(self.top, text="(s)", width=60).grid(row=1,
                                                                     column=2)

                newline = Message(self.top, text=" ").grid(row=2)

                button = Button(self.top,
                                text='Enter',
                                command=lambda: self.enter_task(event)).grid(
                                    row=3, column=1)
                button_cancel = Button(self.top,
                                       text='Cancel',
                                       command=self.cancel_task).grid(row=3,
                                                                      column=2)

                center(self.top)
Ejemplo n.º 5
0
    def concolefooter(self):
        footerframe = Frame(self.master)
        footerframe.config(padx=5, pady=5, bg=Styles.colours["darkGrey"])
        title = Message(footerframe, text="Console:",
                        justify=CENTER, bg=Styles.colours["darkGrey"],
                        foreground=Styles.colours["yellow"],
                        width=100, font=Styles.fonts["entry"])

        consoletext = Text(footerframe, height=5, width=80, bg=Styles.colours["darkGrey"],
                           foreground=Styles.colours["grey"], state=NORMAL, relief=FLAT, font=Styles.fonts["console"])
        consoletext.insert(END, "Welcome to Project Bi")
        consoletext.config(state=DISABLED)
        self.console.setconsolefield(consoletext)
        scroll = Scrollbar(footerframe, command=consoletext.yview, relief=FLAT)
        consoletext.configure(yscrollcommand=scroll.set)

        self.boptimize = yellowbutton(footerframe, "Optimize", 20, lambda e: self.observerstage())
        deactivatebutton(self.boptimize)
        self.boptimize.pack(side=RIGHT, fill=BOTH, padx=5, pady=5)
        self.boptimize.configure(font=Styles.fonts["h1Button"])

        title.pack(side=LEFT, fill=BOTH)
        scroll.pack(side=LEFT, fill=BOTH)
        consoletext.pack(side=LEFT, fill=BOTH)
        footerframe.grid(row=2, column=0, sticky=W + E + N + S, columnspan=2)

        return footerframe
def about():
    help_window = tk.Toplevel(master) 
    help_window.geometry("1000x1000")
    help_window.title("About the Bunimovich Stadia Evolution Viewer")
          
    text = Message(help_window, text = TEXT, padx = 100)
    text.pack()
Ejemplo n.º 7
0
    def __init__(self,
                 master,
                 variable,
                 anchor=W,
                 bordercolor=None,
                 borderwidth=1,
                 padx=0,
                 pady=0,
                 background=None,
                 foreground=None,
                 font=None):
        Cell.__init__(self,
                      master,
                      background=background,
                      highlightbackground=bordercolor,
                      highlightcolor=bordercolor,
                      highlightthickness=borderwidth,
                      bd=0)

        self._message_widget = Message(self,
                                       textvariable=variable,
                                       font=font,
                                       background=background,
                                       foreground=foreground)
        self._message_widget.pack(expand=True,
                                  padx=padx,
                                  pady=pady,
                                  anchor=anchor)
Ejemplo n.º 8
0
class Data_Cell(Cell):
    def __init__(self,
                 master,
                 variable,
                 anchor=W,
                 bordercolor=None,
                 borderwidth=1,
                 padx=0,
                 pady=0,
                 background=None,
                 foreground=None,
                 font=None):
        Cell.__init__(self,
                      master,
                      background=background,
                      highlightbackground=bordercolor,
                      highlightcolor=bordercolor,
                      highlightthickness=borderwidth,
                      bd=0)

        self._message_widget = Message(self,
                                       textvariable=variable,
                                       font=font,
                                       background=background,
                                       foreground=foreground)
        self._message_widget.pack(expand=True,
                                  padx=padx,
                                  pady=pady,
                                  anchor=anchor)

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

    def _on_configure(self, event):
        self._message_widget.configure(width=event.width)
Ejemplo n.º 9
0
 def __setup_instructions(self):
     # Instructions on bottom of screen
     self.instructions = Frame(self.root)
     instruct = Message(self.instructions, text=("Controls: Press Left and Right to change month, Up and Down to "
                                                 "change year, and spacebar to return to the current date"),
                        width=500)
     instruct.grid(columnspan=3)
     self.instructions.grid(sticky="WE", columnspan=3)
Ejemplo n.º 10
0
 def Msg(name):
     master = tk()
     master.title('Error message')
     msg = Message(master, text='unable to load ' + name + ' from file')
     # msg.config()
     msg.pack()
     # close_button = Button(master, text='OK', command=master.destroy)
     mainloop()
Ejemplo n.º 11
0
def About():
    top = Toplevel()
    top.title("About this application...")
    msg = Message(top,
                  text="Turing Machine simulator\nWritten on python 2.7 \
                              using Tkinter\n2016 Kyiv, IASA\nby Illya Barziy")
    msg.pack()
    button = Button(top, text="OK", command=top.destroy)
    button.pack()
 def message_box_notification(self, txt):
     #crate the top level for message box
     mess_box = Toplevel()
     mess_box.title("Message")
     #create the message text
     msg = Message(mess_box, text = txt)
     msg.pack()
     #create top level close button
     mess_box_close = Button(mess_box, text = "OK", command = mess_box.destroy)
     mess_box_close.pack()
Ejemplo n.º 13
0
 def info(self):
     #Infoseite zeigen
     top = Toplevel()
     top.title(u"Über dieses Programm...")
     
     msg = Message(top, text=u'Dieses Programm dient zur Auswertung von Messungen für die Bestimmung des Weiterreißwiderstands nach DIN ISO 6133:2004-05\n\nZur Detektion der Maxima dient ein Algorithmus aus MATLAB (http://billauer.co.il/peakdet.html) verwendet, welcher nach Python übersetzt wurden.\n\nDas Programm entscheidet je nach Anzahl der Maxima selbst, welche Vorgabe für die Auswertung zu verwenden ist.\n\n\n\nErstellt von Lukas Scheffler')
     msg.pack()
     
     button = Button(top, text="Verbergen", command=top.destroy)
     button.pack()
Ejemplo n.º 14
0
	def onSetParams(self):
		top = Toplevel(self.parent)
		top.title("Model Setup")
		msg = Message(top, text="")
		msg.pack()
		
		applyb = Button(top, text="Apply", command=top.destroy)
		closeb = Button(top, text="Close", command=top.destroy)
		applyb.pack()
		closeb.pack()
Ejemplo n.º 15
0
class Scroller(object):
    """
    Scrolls through a solution list.
    """
    def __init__(self, wdw, sols):
        """
        Stores the list of solutions in sols
        and defines the layout of the GUI.
        """
        wdw.title('solutions scroller')
        self.sols = sols
        self.cursor = 0
        self.lbl = Label(wdw, text="solution : ")
        self.lbl.grid(row=0, column=0, sticky=E)
        self.ent = Entry(wdw)
        self.ent.grid(row=0, column=1, stick=W)
        self.ent.insert(INSERT, "0 of %d" % len(sols))
        self.myft = Font(family="Courier New", size=12, weight="normal")
        self.mlen = self.myft.measure("M")
        lines = sols[0].split('\n')
        self.width = max([len(line) for line in lines])
        self.display = StringVar()
        self.display.set(self.sols[0])
        self.mess = Message(wdw, textvariable=self.display, \
            font=self.myft, width=self.width*self.mlen, background='white')
        self.mess.grid(row=1, column=0, columnspan=2)
        self.btnext = Button(wdw, command=self.next, text='next')
        self.btnext.grid(row=2, column=1, sticky=W + E)
        self.btprev = Button(wdw, command=self.previous, text='previous')
        self.btprev.grid(row=2, column=0, sticky=W + E)

    def show(self):
        """
        Shows the solution at position self.cursor
        in the message widget and updates the entry widget.
        """
        self.display.set(self.sols[self.cursor])
        self.ent.delete(0, END)
        self.ent.insert(INSERT, '%d of %d' % (self.cursor, len(self.sols)))

    def next(self):
        """
        Increases the cursor by one if possible.
        """
        if self.cursor < len(self.sols) - 1:
            self.cursor = self.cursor + 1
        self.show()

    def previous(self):
        """
        Decreases the cursor by one if possible.
        """
        if self.cursor > 0:
            self.cursor = self.cursor - 1
        self.show()
Ejemplo n.º 16
0
class Scroller(object):
    """
    Scrolls through a solution list.
    """
    def __init__(self, wdw, sols):
        """
        Stores the list of solutions in sols
        and defines the layout of the GUI.
        """
        wdw.title('solutions scroller')
        self.sols = sols
        self.cursor = 0
        self.lbl = Label(wdw, text="solution : ")
        self.lbl.grid(row=0, column=0, sticky=E) 
        self.ent = Entry(wdw)
        self.ent.grid(row=0, column=1, stick=W)
        self.ent.insert(INSERT, "0 of %d" % len(sols))
        self.myft = Font(family="Courier New", size=12, weight="normal")
        self.mlen = self.myft.measure("M")
        lines = sols[0].split('\n')
        self.width = max([len(line) for line in lines])
        self.display = StringVar()
        self.display.set(self.sols[0])
        self.mess = Message(wdw, textvariable=self.display, \
            font=self.myft, width=self.width*self.mlen, background='white')
        self.mess.grid(row=1, column=0, columnspan=2)
        self.btnext = Button(wdw, command=self.next, text='next')
        self.btnext.grid(row=2, column=1, sticky=W+E)
        self.btprev = Button(wdw, command=self.previous, text='previous')
        self.btprev.grid(row=2, column=0, sticky=W+E)

    def show(self):
        """
        Shows the solution at position self.cursor
        in the message widget and updates the entry widget.
        """
        self.display.set(self.sols[self.cursor])
        self.ent.delete(0, END)
        self.ent.insert(INSERT, '%d of %d' % (self.cursor, len(self.sols)))

    def next(self):
        """
        Increases the cursor by one if possible.
        """
        if self.cursor < len(self.sols) - 1:
            self.cursor = self.cursor + 1
        self.show()

    def previous(self):
        """
        Decreases the cursor by one if possible.
        """
        if self.cursor > 0:
            self.cursor = self.cursor - 1
        self.show()
Ejemplo n.º 17
0
def make_error_dialog(player_dlg):
    error_dlg = Toplevel(master=player_dlg);
    error_dlg.title( "Error" );
    error_dlg.grab_set();
    error_msg = Message(error_dlg, aspect=300, text="Player count must be between %d and %d" % (MIN_PLAYER_COUNT, MAX_PLAYER_COUNT) )
    error_msg.pack();
    error_button = Button(error_dlg, text="OK", \
                            command=error_dlg.destroy);
    error_button.pack();
    error_dlg.update();
    return
Ejemplo n.º 18
0
class Data_Cell(Cell):
    def __init__(self, master, variable, anchor=W, bordercolor=None, borderwidth=1, padx=0, pady=0, background=None, foreground=None, font=None):
        Cell.__init__(self, master, background=background, highlightbackground=bordercolor, highlightcolor=bordercolor, highlightthickness=borderwidth, bd= 0)

        self._message_widget = Message(self, textvariable=variable, font=font, background=background, foreground=foreground)
        self._message_widget.pack(expand=True, padx=padx, pady=pady, anchor=anchor)

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

    def _on_configure(self, event):
        self._message_widget.configure(width=event.width)
Ejemplo n.º 19
0
	def help_f(self):
		top = Toplevel()
		top.title("HELP")
		msg = Message(top, width= 500,
                 text="Noise Threshold (NT) - Noise Based Main Threshold \
(Sigmas)\n Threshold 1 - Main Threshold (LSBs) \n Threshold 2 - End of Pulse Error \n \
Threshold 3 - End of Tail Error \n When Thr1 = Thr3 = 0 their values are defined as: \n \
(THR1 = NT (LSBs) / THR3 = NT*NOISE_ADC / 5)")
		msg.pack()

		button = Button(top, text="Close", command=top.destroy)
		button.pack()
Ejemplo n.º 20
0
class Data_Cell(Cell):
    """
     A Class used as a data cell for a table widget

    Methods
    -------
    _on_configure()
            Description | Message widget configuration

    """
    def __init__(self,
                 master,
                 variable,
                 anchor=CENTER,
                 bordercolor=None,
                 borderwidth=1,
                 padx=0,
                 pady=0,
                 background=None,
                 foreground=None,
                 font=None):
        """
        Parameters
        ----------

        :param master: the master of the data cell
        :param variable: data variable
        :param anchor: anchor
        :param bordercolor: the color of the border
        :param borderwidth: the width of the data cell border
        :param padx: x coordinate padding
        :param pady: y coordinate padding
        :param background: background color
        :param foreground: foreground color
        :param font: text font
        """
        Cell.__init__(self,
                      master,
                      background=background,
                      highlightbackground=bordercolor,
                      highlightcolor=bordercolor,
                      highlightthickness=borderwidth,
                      bd=0)

        self._message_widget = Message(self,
                                       textvariable=variable,
                                       font=font,
                                       background=background,
                                       foreground=foreground)

        self._message_widget.pack(padx=padx, pady=pady, anchor=anchor)

        self._message_widget.configure(width=110, pady=1.2)
Ejemplo n.º 21
0
    def help_f(self):
        top = Toplevel()
        top.title("HELP")
        msg = Message(top,
                      width=500,
                      text="Noise Threshold (NT) - Noise Based Main Threshold \
(Sigmas)\n Threshold 1 - Main Threshold (LSBs) \n Threshold 2 - End of Pulse Error \n \
Threshold 3 - End of Tail Error \n When Thr1 = Thr3 = 0 their values are defined as: \n \
(THR1 = NT (LSBs) / THR3 = NT*NOISE_ADC / 5)")
        msg.pack()

        button = Button(top, text="Close", command=top.destroy)
        button.pack()
Ejemplo n.º 22
0
class Panle:
    def __init__(self, master):
        
        self.frame = Frame(master)
        self.frame.pack(side=TOP)
        self.label = Tkinter.Label(self.frame, text='wordEcho')
        self.label.pack()
        self.input = Entry(self.frame, width=45)
        self.input.pack(side=LEFT)
        self.button = Button(self.frame, text='翻译')
        self.button.pack(side=RIGHT)
        self.frame2 = Scrollbar(master)
        self.frame2.pack(side=TOP)
        self.ms = Message(self.frame2,  anchor='w', width=150)
        self.ms.pack()
Ejemplo n.º 23
0
 def encrypt_input():
     ourMessage = ''
     for i in range(len(encryptedinput)):
         ourMessage += encryptedinput[i]
     messageVar = Message(inputwindow, text=ourMessage)
     messageVar.config(bg='lightgray')
     messageVar.config(aspect=400)
     messageVar.grid()
Ejemplo n.º 24
0
class AlreadyExistsDialog(Dialog):
    def __init__(self, master_frame, new, old, variable, class_=None, relx=0.5, rely=0.3):
        Dialog.__init__(self, master_frame, 'Warning!',
                        class_, relx, rely)
        self.new = new
        self.old = old
        self.variable = variable
        
        self.text = "Warning: Customer Found with the same name.\n" + \
        "\nNew record: " + new[1] + " " + new[2] + " " + new[0] + \
        " (" + new[3] + ") - " + new[4].strftime("%m/%d/%Y") + \
        "\nOld record: " + old[1] + " " + old[2] + " " + old[0] + \
        " (" + old[3] + ") - " + old[4].strftime("%m/%d/%Y") + \
        "\n\n Cancel to edit entry, Override to replace old entry."
        

    def show(self):
        self.setup()

        self.msg = Message(self.root, text=self.text, aspect=400)
        self.msg.pack(expand=True, fill=BOTH)

        self.frame = Frame(self.root)
        
        b1 = Button(self.frame, text="Cancel", command=self.cancel)
        b1.pack(side=LEFT, fill=BOTH, expand=True, padx=10)
        b2 = Button(self.frame, text="Override", command=self.replace)
        b2.pack(side=LEFT, fill=BOTH, expand=True, padx=10)
        #b3 = Button(self.frame, text="Add Duplicate", command=self.add_duplicate)
        #b3.pack(side=LEFT, fill=BOTH, expand=True)
        
        self.frame.pack(padx=10, pady=10)

        self.root.bind('<Return>', self.cancel)
        
        self.enable()

    def cancel(self, event=None):
        self.variable.set(0)
        self.root.quit()

    def replace(self):
        self.variable.set(1)
        self.root.quit()

    def add_duplicate(self):
        self.variable.set(2)
        self.wm_delete_window()
Ejemplo n.º 25
0
 def __init__(self, wdw, sols):
     """
     Stores the list of solutions in sols
     and defines the layout of the GUI.
     """
     wdw.title('solutions scroller')
     self.sols = sols
     self.cursor = 0
     self.lbl = Label(wdw, text="solution : ")
     self.lbl.grid(row=0, column=0, sticky=E) 
     self.ent = Entry(wdw)
     self.ent.grid(row=0, column=1, stick=W)
     self.ent.insert(INSERT, "0 of %d" % len(sols))
     self.myft = Font(family="Courier New", size=12, weight="normal")
     self.mlen = self.myft.measure("M")
     lines = sols[0].split('\n')
     self.width = max([len(line) for line in lines])
     self.display = StringVar()
     self.display.set(self.sols[0])
     self.mess = Message(wdw, textvariable=self.display, \
         font=self.myft, width=self.width*self.mlen, background='white')
     self.mess.grid(row=1, column=0, columnspan=2)
     self.btnext = Button(wdw, command=self.next, text='next')
     self.btnext.grid(row=2, column=1, sticky=W+E)
     self.btprev = Button(wdw, command=self.previous, text='previous')
     self.btprev.grid(row=2, column=0, sticky=W+E)
Ejemplo n.º 26
0
    def __init__(self, wdgt, delay=1, follow=True):
        """
        Initialize the ToolTip

        Arguments:
          wdgt: The widget this ToolTip is assigned to
          msg:  A static string message assigned to the ToolTip
          msgFunc: A function that retrieves a string to use as the ToolTip text
          delay:   The delay in seconds before the ToolTip appears(may be float)
          follow:  If True, the ToolTip follows motion, otherwise hides
        """
        self.wdgt = wdgt
        # The parent of the ToolTip is the parent of the ToolTips widget
        self.parent = self.wdgt.master
        # Initalise the Toplevel
        Toplevel.__init__(self, self.parent, bg='black', padx=1, pady=1)
        # Hide initially
        self.withdraw()
        # The ToolTip Toplevel should have no frame or title bar
        self.overrideredirect(True)

        # The msgVar will contain the text displayed by the ToolTip
        self.msgVar = StringVar()
        self.delay = delay
        self.follow = follow
        self.visible = 0
        self.lastMotion = 0
        Message(self, textvariable=self.msgVar, bg='#FFFFDD',
                aspect=1000).grid()                                           # The test of the ToolTip is displayed in a Message widget
Ejemplo n.º 27
0
def main():
    root = Tk()
    if (len(sys.argv) > 1):
        mol_filename = sys.argv[1]
    else:
        #print >> sys.stderr, "Syntax: %s <mol file> [<svg file>]" % sys.argv[0]
        mol_filename = askopenfilename(parent=root,
                                       title="Pick a MOL file to plot",
                                       filetypes=[("MOL files", "*.mol"),
                                                  ("All Files", "*")])
        if (mol_filename == ''):
            sys.exit(-1)

    if (len(sys.argv) > 2):
        svg_filename = sys.argv[2]
    else:
        svg_filename = None

    if (not os.path.isfile(mol_filename)):
        print >> sys.stderr, "File not found: " + mol_filename
        sys.exit(-2)

    #file = open(mol_filename)
    try:
        G = molfile2graph(mol_filename)
    except Exception, strerror:
        root.title("ERROR")
        Message(root, text=strerror, width=100).pack()
        Button(root, text="OK", command=root.destroy).pack()
        root.mainloop()
        sys.exit(-1)
Ejemplo n.º 28
0
 def change_var(*args):
     try:
         if self.text_to_img[self.variable.get()]:
             #print(self.variable.get())
             bg = background
             fg = foreground
             if self._message_widget:
                 bg = self._message_widget.cget('background')
                 fg = self._message_widget.cget('foreground')
             self._message_widget.pack_forget()
             self._message_widget = Label(
                 self,
                 width=width,
                 background=bg,
                 foreground=fg,
                 image=self.text_to_img[self.variable.get()])
             self._message_widget.pack(expand=True,
                                       padx=padx,
                                       pady=pady,
                                       anchor=anchor)
             self._message_widget.bind(
                 '<Button-1>',
                 lambda event, row=self.row_num, table=self.table:
                 cell_selected(event, table, row))
     except KeyError as e:
         pass
     return
Ejemplo n.º 29
0
    def __init__(self, master, console,params,maingui):
        self.frame = Frame(master)
        self.frame.config(padx=5, pady=5, bg=Styles.colours["darkGrey"])
        self.frame.grid(row=0, column=0, sticky=W + E + N + S,columnspan=2)
        self.title = Message(self.frame, text="ProjectB: Selection",
                        justify=CENTER, bg=Styles.colours["darkGrey"],
                        foreground=Styles.colours["yellow"],
                        width=300, font=Styles.fonts["h1"])

        def importsettings(event):
            f = tkFileDialog.askopenfilename(parent=master, title='Choose a file')
            parsemodifycustomvar(params,parsein(f,parseintosimple(params),console))
            maingui.ready("model")
            maingui.ready("bayes")

        def exportfile(event):
            f = tkFileDialog.asksaveasfilename(parent=master, title='Choose a file')
            parseout(f,parseintosimple(params),console)

        self.bimport = camobutton(self.frame, "Import Settings", 15,importsettings)
        self.bexport = camobutton(self.frame, "Export Settings", 15,exportfile)
        self.badvset = yellowbutton(self.frame, "Advanced Settings", 20)

        self.badvset.bind("<Button-1>", lambda a: AdvancedSettings(console,params))
        self.qb = qbutton(self.frame)

        self.title.pack(side=LEFT, fill=BOTH, padx=5, pady=5)
        self.qb.pack(side=RIGHT, fill=BOTH, padx=5, pady=5)
        self.badvset.pack(side=RIGHT, fill=BOTH, padx=5, pady=5)
        self.bexport.pack(side=RIGHT, fill=BOTH, padx=5, pady=5)
        self.bimport.pack(side=RIGHT, fill=BOTH, padx=5, pady=5)
Ejemplo n.º 30
0
    def __init__(self, frame, **kwargs):
        text = get_dict_item(kwargs, 'text', 'None')
        font = get_dict_item(kwargs, 'font', 'Arial')
        width = get_dict_item(kwargs, 'width', '+10')
        height = get_dict_item(kwargs, 'height', '+5')
        self.fg = get_dict_item(kwargs, 'fg', 'black')
        self.fg_hov = get_dict_item(kwargs, 'fg_hov', '')
        self.bg = get_dict_item(kwargs, 'bg', '')
        self.bg_hov = get_dict_item(kwargs, 'bg_hov', '')
        self.function = get_dict_item(kwargs, 'func', 'False')
        self.function_exc = get_dict_item(kwargs, 'command', 'False')
        self.img = get_dict_item(kwargs, 'img', '')
        self.img_hov = get_dict_item(kwargs, 'img_hov', '')

        if self.img == '':
            self.msg = Message(frame, text=text)
            self.msg.config(bg=self.bg, fg=self.fg, width=width, font=font)
        else:
            self.msg = Label(frame,
                             image=self.img,
                             width=width,
                             background=self.bg)

        self.msg.bind("<Enter>", self._enter)
        self.msg.bind("<Leave>", self._leave)
        self.msg.bind("<Button-1>", self._click)
Ejemplo n.º 31
0
    def help_f(self):
		top = Toplevel()
		top.title("HELP")
		msg = Message(top, width= 500,
             text="COEFF Calibration Procedure: \n \
             Input Start Point and Length of the pulse \n \
             Input an initial guess of the pulse amplitude \n \
             Use a ROI with at least 1000 samples of baseline \n \
             and 1000 samples after pulse end \n \
             Adjust loop range and step until a graph error \n \
             with a minimum is observed \n \
             Refine the search to increase precision")
		msg.pack()

		button = Button(top, text="Close", command=top.destroy)
		button.pack()
Ejemplo n.º 32
0
    def help_f(self):
        top = Toplevel()
        top.title("HELP")
        msg = Message(top,
                      width=500,
                      text="COEFF Calibration Procedure: \n \
             Input Start Point and Length of the pulse \n \
             Input an initial guess of the pulse amplitude \n \
             Use a ROI with at least 1000 samples of baseline \n \
             and 1000 samples after pulse end \n \
             Adjust loop range and step until a graph error \n \
             with a minimum is observed \n \
             Refine the search to increase precision")
        msg.pack()

        button = Button(top, text="Close", command=top.destroy)
        button.pack()
Ejemplo n.º 33
0
 def render_header(self, title, buttons):
     Label(self.tk, text=title, font=("Helvetica", 20)).pack()
     Message(self.tk,
             textvariable=self.info_label_text,
             fg="red",
             justify=LEFT,
             width=500).pack()
     self.render_window_frames()
     for i in xrange(len(buttons)):
         Button(self.header_frame,
                text=buttons[i]['title'],
                command=buttons[i]['callback']).pack(side=LEFT)
Ejemplo n.º 34
0
 def create_widgets(self):
     """Creates buttons on the window and binds actions to them"""
     #listbox for the equations
     self.fields = Listbox(self, selectmode=SINGLE)
     self.fields.config(width=100)
     self.fields.pack()
     #button for calculating
     self.calculate_button = Button(self)
     self.calculate_button["text"] = "Calculate"
     self.calculate_button["command"] = self.calculate
     self.calculate_button.pack({"side": "left"})
     #to the end
     self.show_result_floating = Message(self, width=250)
     self.show_result_floating.pack()
     #second Message
     self.show_result_interval = Message(self, width=250)
     self.show_result_interval.pack()
     #adding menu buttons to the window
     self.menubar = Menu(self)
     self.menubar.add_command(label="Load file", command=self.read_json_file)
     self.menubar.add_command(label="Quit", command=self.quit)
Ejemplo n.º 35
0
def OnButtonClick():
    

    e2.focus_set()
    e2.selection_range(0, END)

    e3.focus_set()
    e3.selection_range(0, END)

    e4.focus_set()
    e4.selection_range(0, END)
    
    win = Toplevel()
    win.title("Program Answer")
    if len(oracle_old_connection(e2.get(), e3.get())) > 0:
        cur = oracle_connection()
        alter_string = 'alter user %s identified by %s' % (e2.get(), e4.get())
        cur.execute(alter_string)
        message = "Password Successfully Updated"
        
        msg = Message(win, text=message)
        msg.pack()
        button = Button(win, text='OK', command=win.destroy)
        button.pack()
    else:
        message = "Error!!!!"
        
        msg = Message(win, text=message)
        msg.pack()
        button = Button(win, text='OK', command=win.destroy)
        button.pack()
Ejemplo n.º 36
0
    def __init__(self):
        self.master = Tk()
        self.master.title('About fabian')
        frame = Frame(self.master, width=500, height=400, bd=1)
        frame.pack()

        frameAbout = Frame(frame, bd=0)
        message = \
"""
Key short cuts 

Main window:
  o - open new file
  q - quit application
  C - Close all opened windows 
  z - zoom in
  x - zoom out
  right arrow - next image
  left arrow  - previous image
  a - see "help - about"
  h - see "help - help"
  Change tools:
    F1 - activate zoom tool
    F2 - activate line profile tool
    F3 - activate intensity projections on vertical/horizontal box sides
    F4 - activate relief plot tool
    F5 - activate rocking curve tool
  Control peaks:
    p - show/hide peaks found by ImageD11 peaksearch
    c - clear peaks from memory
    r - read a peaks file (spt)
  Auto update images:
    f - activate/deactivate "File - auto file update"
    up-arrow   - add 0.5 sec. to time delay between 
                 loading files in auto file update mode
    down-arrow - subtract 0.5 sec. from the time delay
                 between loading files in auto file update mode

2D plot window:
  a - auto scale plot
  p - print/save plot
  q - quit 2D plot
"""

        Message(frameAbout, text=message, width=500).pack(fill=X, padx=5)
        frameAbout.pack(expand=1, pady=10, padx=5)

        frameAbout = Frame(frame, bd=0)
        Button(frameAbout,text='So what', bg='red', command=self.quit)\
                                          .pack(side=RIGHT)
        frameAbout.pack(expand=1, pady=10, padx=5)
Ejemplo n.º 37
0
	def drawWindow(self):
		#cache the images to display
		self.redditraw = Image.open("reddit.png").resize((40,40), Image.ANTIALIAS)
		self.redditimg = ImageTk.PhotoImage(self.redditraw)
		
		self.twitterraw = Image.open("twitter.png").resize((40,40), Image.ANTIALIAS)
		self.twitterimg = ImageTk.PhotoImage(self.twitterraw)
		
		for post in self.posts:
			frame = Frame(self)
			frame.pack(side=TOP, fill=X)
			
			#this was for using web images
			#file = cStringIO.StringIO(urllib.urlopen("location").read())
			
			#draw 
			if post.type == "RedditPost":
				reddit = Label(frame, image=self.redditimg)
				reddit.image = self.redditimg
				#reddit.bind("<1>", lambda event, url=post[1]: web.open_new(url))
				reddit.pack(side=LEFT)
			else:
				twitter = Label(frame, image=self.twitterimg)
				twitter.image = self.twitterimg
				#twitter.bind("<1>", lambda event, url=post[1]: web.open_new(url))
				twitter.pack(side=LEFT)
			
			body = Frame(frame)
			body.pack(fill=BOTH)
			
			#the actual post body
			title = Message(body, text=post.title, foreground="#0000dd", justify=LEFT, width=550)
			#title.bind("<1>", lambda event, url=post[4]: web.open_new(url))
			title.pack(anchor=W)
			
			#date and author
			details = Label(body, text=post.date+" by "+post.user)
			details.pack(anchor=W)
Ejemplo n.º 38
0
	def path(self):
		path_frame=LabelFrame(self.window,text='Input paths',width=450,height=100)
		path_frame.place(x=20,y=60)

		ora_mes=Message(path_frame,text='Excel from ORA:',width=120)
		ora_mes.place(x=10,y=0)
		self.ora_entry=Entry(path_frame,textvariable=self.ora_path,width=35)
		self.ora_entry.place(x=130,y=0)
		ora_button=Button(path_frame,text='Select…',command=self.selectPath1)
		ora_button.place(x=365,y=0)

		calcu_mes=Message(path_frame,text='Calculator:',width=120)
		calcu_mes.place(x=10,y=40)
		self.calcu_entry=Entry(path_frame,textvariable=self.calcu_path,width=35)
		self.calcu_entry.place(x=130,y=40)
		calcu_button=Button(path_frame,text='Select…',command=self.selectPath2)
		calcu_button.place(x=365,y=40)
Ejemplo n.º 39
0
 def create_widgets(self):
     self.name = StringVar(self.parent)
     self.fontSize = StringVar(self.parent)
     self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
     self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
     self.messageInfo = Message(self.frameMain, anchor=W, justify=LEFT,
                 padx=5, pady=5, text=self.message) #,aspect=200)
     entryName = Entry(self.frameMain, textvariable=self.name, width=30)
     entryName.focus_set()
     self.messageInfo.pack(padx=5, pady=5) #, expand=TRUE, fill=BOTH)
     entryName.pack(padx=5, pady=5)
     frameButtons = Frame(self, pady=2)
     frameButtons.pack(side=BOTTOM)
     self.buttonOk = Button(frameButtons, text='Ok',
             width=8, command=self.Ok)
     self.buttonOk.pack(side=LEFT, padx=5)
     self.buttonCancel = Button(frameButtons, text='Cancel',
             width=8, command=self.Cancel)
     self.buttonCancel.pack(side=RIGHT, padx=5)
Ejemplo n.º 40
0
    def show(self):
        self.setup()

        self.msg = Message(self.root, text=self.text, aspect=400)
        self.msg.pack(expand=True, fill=BOTH)

        self.frame = Frame(self.root)
        
        b1 = Button(self.frame, text="Cancel", command=self.cancel)
        b1.pack(side=LEFT, fill=BOTH, expand=True, padx=10)
        b2 = Button(self.frame, text="Override", command=self.replace)
        b2.pack(side=LEFT, fill=BOTH, expand=True, padx=10)
        #b3 = Button(self.frame, text="Add Duplicate", command=self.add_duplicate)
        #b3.pack(side=LEFT, fill=BOTH, expand=True)
        
        self.frame.pack(padx=10, pady=10)

        self.root.bind('<Return>', self.cancel)
        
        self.enable()
Ejemplo n.º 41
0
    def __init__(self):
        self.master = Tk()
        self.master.title('About fabian')
        frame = Frame(self.master, width=500, height=400, bd=1)
        frame.pack()

        frameAbout = Frame(frame, bd=0)
        message = "\nfabian (%s) was brought to you by \n\n\
Henning O. Sorensen & Erik Knudsen\n\
Center for Fundamental Research: Metal Structures in Four Dimensions\n\
Risoe National Laboratory\n\
Frederiksborgvej 399\n\
DK-4000 Roskilde\n\
email: [email protected]"%(Fabian.__version__)

        Message(frameAbout, text=message,width=500).pack(fill=X, padx=5)
        frameAbout.pack(expand=1, pady=10, padx=5)

        frameAbout = Frame(frame, bd=0)
        Button(frameAbout,text='So what', bg='red', command=self.quit)\
                                          .pack(side=RIGHT)
        frameAbout.pack(expand=1, pady=10, padx=5)
Ejemplo n.º 42
0
 def help(self):
     #Hilfeseite zeigen
     top = Toplevel()
     top.title("Hilfe")
     
     label1 = ttk.Label(top, text = u"Projekt öffnen/erstellen", font=self.normal_font)
     label1.pack()
     
     msg1 = Message(top, text=u'Über Datei -> Neu muss zu Beginn eine .txt-Datei erstellt werden. In dieser werden die Ergebnisse der Auswertung gespeichert.\n\nAlternativ kann über Datei -> Öffnen... ein bereits existierendes Projekt mit den neuen Ergebnissen erweitert werden. \n\n')
     msg1.pack()
     
     label2 = ttk.Label(top, text = u"Messung importieren und auswerten", font=self.normal_font)
     label2.pack()
     
     msg2 = Message(top, text=u'Zunächst muss über Datei -> Messung importieren die gewünschte Messung importiert werden.\n\nAnschließend werden Delta X und Delta Y so eingestellt, dass nur die gewünschten Maxima (rote Punkte im Graphen) vom Algorithmus erkannt werden.\n\nZur Berechnung des Weiterreißwiderstandes wird die Probendicke benötigt. Diese muss im entsprechenden Fenster eingetragen werden (Trennung durch . nicht durch ,  Bsp: 1.75).\n\nÜber die Schaltfläche Berechnen werden die gewünschten Werte berechnet.\n\nNachdem der Probenname und optional ein Kommentar zur Messung in die entsprechenden Fenster eingetragen wurden, lässt sich die Auswertung im zuvor gewählten Projekt abspeichern.')
     msg2.pack()
     
     button = Button(top, text="Verbergen", command=top.destroy)
     button.pack()
Ejemplo n.º 43
0
class Application(Frame):
    """Main application class"""
    json_file_name = "functions.json" # should be none after tests
    json_data = None
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.create_widgets()
        master.title("Regula falsi")
        master.minsize(width=100, height=100)
        master.config(menu=self.menubar)

    def calculate(self):
        """Does all the work"""
        item_number = self.fields.curselection()
        polynomial = self.json_data["functions"][int(item_number[0])]
        result_floating = None
        result_interval = None
        if self.json_data["method"] == "regula_falsi":
            try:
                result_floating = regula_falsi(polynomial["a"],
                                               polynomial["b"],
                                               function_from_list,
                                               polynomial["coeff"]
                                              )
            except MyError as error:
                result_floating = error.value
            except ZeroDivisionError:
                result_floating = "Unfortunately, division by 0 happened"
            try:
                result_interval = regula_falsi_interval(polynomial["a"],
                                                        polynomial["b"],
                                                        function_from_list,
                                                        polynomial["coeff"]
                                                       )
                result_interval = result_interval.format('%.20E')[9:]
                result_interval = result_interval[:-1]
            except MyError as error:
                result_interval = error.value
        elif self.json_data["method"] == "newton":
            try:
                result_floating = newton(polynomial["x"],
                                         polynomial["epsilon"],
                                         polynomial["max_iterations"],
                                         function_from_list,
                                         polynomial["coeff"],
                                         polynomial["derivative_coeff"]
                                        )
            except ZeroDivisionError:
                result_floating = "Unfortunately, division by zero happened"
            except MyError as error:
                result_floating = error.value
            try:
                result_interval = newton_interval(polynomial["x"],
                                                  polynomial["epsilon"],
                                                  polynomial["max_iterations"],
                                                  function_from_list,
                                                  polynomial["coeff"],
                                                  polynomial["derivative_coeff"]
                                                 )
                result_interval = result_interval.format('%.20E')[9:]
                result_interval = result_interval[:-1]
            except MyError as error:
                result_interval = error.value
        else:
            result_interval = "You propably"
            result_floating = "gave me wrong JSON"
        self.show_result_floating.config(text=result_interval)
        self.show_result_interval.config(text=result_floating)

    def read_json_file(self):
        """Reads function coefficients from json files"""
        self.fields.delete(0, END)
        self.json_file_name = load_file()
        with open(self.json_file_name) as json_file:
            self.json_data = json.load(json_file)
        for item in self.json_data["functions"]:
            self.fields.insert(END, item["coeff"])

    def create_widgets(self):
        """Creates buttons on the window and binds actions to them"""
        #listbox for the equations
        self.fields = Listbox(self, selectmode=SINGLE)
        self.fields.config(width=100)
        self.fields.pack()
        #button for calculating
        self.calculate_button = Button(self)
        self.calculate_button["text"] = "Calculate"
        self.calculate_button["command"] = self.calculate
        self.calculate_button.pack({"side": "left"})
        #to the end
        self.show_result_floating = Message(self, width=250)
        self.show_result_floating.pack()
        #second Message
        self.show_result_interval = Message(self, width=250)
        self.show_result_interval.pack()
        #adding menu buttons to the window
        self.menubar = Menu(self)
        self.menubar.add_command(label="Load file", command=self.read_json_file)
        self.menubar.add_command(label="Quit", command=self.quit)
Ejemplo n.º 44
0
def infov(f, text,textv,row,col):
     m = Message(f, text=text, font=Styles.fonts["h2"], bg=Styles.colours["grey"],width=200)
     v = Message(f, text=textv, font=Styles.fonts["h3"], bg=Styles.colours["grey"],width=200)
     m.grid(row=row,column=col)
     v.grid(row=row+1,column=col)
     return (m,v)
print "Script running at: " + runningPath

#Build Root UI Window
root1 = tk.Tk()
root1.iconbitmap(
    'C:\Users\Landon\Desktop\Python Workspace\Steam-Library-Exporter\steambmp.ico'
)
root1.wm_title('Steam Library Exporter v0.9')
root1.tk_setPalette(background="#FFFFFF", foreground="black")

#Build Text & Entry Window Elements
packable_update = Label(root1, text='Ready!')

welcomeMessage = "Welcome to Steam Library Exporter!"
secondMessage = "This app gathers your entire Steam library from the web and all available stats within. \nIt even generates a handy Excel/Numbers spreadsheet for you!"
welcome1 = Message(root1, text=welcomeMessage, width=500, justify='center')
welcome2 = Message(root1, text=secondMessage, width=500, justify='center')

label = tk.Label(root1, text='Enter your Steam Login ID: ')
entry = tk.Entry(root1)
entry.focus_set()

#Image UI
steamLogo = ImageTk.PhotoImage(
    Image.open(
        'C:\Users\Landon\Desktop\Python Workspace\Steam-Library-Exporter\steamExporterBanner.png'
    ))
panel = tk.Label(root1, image=steamLogo)

"------------------------------------- MAIN METHOD -------------------------------------"
Ejemplo n.º 46
0
    def initUI(self):
        
        self.parent.title("Drone control")
        self.style = Style()
        self.style.theme_use("default")
        
        self.pack(fill=BOTH, expand=1)
        
        self.parent.bind_all("<Key>", self._keyDown)
        self.parent.bind_all("<KeyRelease>", self._keyUp)

        if system() == "Linux":
            self.parent.bind_all("<Button-4>", self._onMouseWheelUp)
            self.parent.bind_all("<Button-5>", self._onMouseWheelDown)

        else:
            #case of Windows
            self.parent.bind_all("<MouseWheel>", self._onMouseWheel)
        
        #Commands        
        commandsFrame = tkFrame(self)
        commandsFrame.grid(column=0, row=0, sticky="WE")
        
        self._started = IntVar()
        self._startedCB = Checkbutton(commandsFrame, text="On", variable=self._started, command=self._startedCBChanged)
        self._startedCB.pack(side=LEFT, padx=4)
        
#         self._integralsCB = Checkbutton(commandsFrame, text="Int.", variable=self._integralsEnabled, \
#                                         command=self._integralsCBChanged, state=DISABLED)
#         self._integralsCB.pack(side=LEFT, padx=4)
        
        self._quitButton = Button(commandsFrame, text="Quit", command=self.exit)
        self._quitButton.pack(side=LEFT, padx=2, pady=2)
        
#         self._angleLbl = Label(commandsFrame, text="Angle")
#         self._angleLbl.pack(side=LEFT, padx=4)
#         
#         self._angleEntry = Entry(commandsFrame, state=DISABLED)
#         self._angleEntry.pack(side=LEFT)
        
        #Info
        infoFrame = tkFrame(self)
        infoFrame.grid(column=1, row=1, sticky="NE", padx=4)
        
        #Throttle
        Label(infoFrame, text="Throttle").grid(column=0, row=0, sticky="WE")        
        self._throttleTexts = [StringVar(),StringVar(),StringVar(),StringVar()]
        Entry(infoFrame, textvariable=self._throttleTexts[3], state=DISABLED, width=5).grid(column=0, row=1)                
        Entry(infoFrame, textvariable=self._throttleTexts[0], state=DISABLED, width=5).grid(column=1, row=1)
        Entry(infoFrame, textvariable=self._throttleTexts[2], state=DISABLED, width=5).grid(column=0, row=2)
        Entry(infoFrame, textvariable=self._throttleTexts[1], state=DISABLED, width=5).grid(column=1, row=2)
        
        #Angles
        Label(infoFrame, text="Angles").grid(column=0, row=3, sticky="WE")        
        self._angleTexts = [StringVar(),StringVar(),StringVar()]
        for index in range(3):
            Entry(infoFrame, textvariable=self._angleTexts[index], state=DISABLED, width=5).grid(column=index, row=4)
               
        #Accels
        Label(infoFrame, text="Accels").grid(column=0, row=5, sticky="WE")
        self._accelTexts = [StringVar(),StringVar(),StringVar()]
        for index in range(3):
            Entry(infoFrame, textvariable=self._accelTexts[index], state=DISABLED, width=5).grid(column=index, row=6)
        
        #Speeds
        Label(infoFrame, text="Speeds").grid(column=0, row=7, sticky="WE")
        self._speedTexts = [StringVar(),StringVar(),StringVar()]
        for index in range(3):
            Entry(infoFrame, textvariable=self._speedTexts[index], state=DISABLED, width=5).grid(column=index, row=8)
        
        #Height
        Label(infoFrame, text="Height").grid(column=0, row=9, sticky="E")
        self._heightText = StringVar()
        Entry(infoFrame, textvariable=self._heightText, state=DISABLED, width=5).grid(column=1, row=9)
        
        #Loop rate
        Label(infoFrame, text="Loop @").grid(column=0, row=10, sticky="E")
        self._loopRateText = StringVar()
        Entry(infoFrame, textvariable=self._loopRateText, state=DISABLED, width=5).grid(column=1, row=10)
        Label(infoFrame, text="Hz").grid(column=2, row=10, sticky="W")
        
        #control
        
        controlFrame = tkFrame(self)
        controlFrame.grid(column=0, row=1, sticky="W")
        
        self._throttle = DoubleVar()
        
        if Cockpit.THROTTLE_BY_USER:

            self._thrustScale = Scale(controlFrame, orient=VERTICAL, from_=100.0, to=0.0, \
                                tickinterval=0, variable=self._throttle, resolution=Cockpit.THROTTLE_RESOLUTION, \
                                length=200, showvalue=1, \
                                state=DISABLED,
                                command=self._onThrustScaleChanged)

        else:
        
            self._thrustScale = Scale(controlFrame, orient=VERTICAL, from_=100.0, to=-100.0, \
                                tickinterval=0, variable=self._throttle, \
                                length=200, showvalue=1, \
                                state=DISABLED,
                                command=self._onThrustScaleChanged)

        self._thrustScale.bind("<Double-Button-1>", self._onThrustScaleDoubleButton1, "+")
        self._thrustScale.grid(column=0)
        
        self._shiftCanvas = Canvas(controlFrame, bg="white", height=400, width=400, \
                             relief=SUNKEN)
        self._shiftCanvas.bind("<Button-1>", self._onMouseButton1)
        #self._shiftCanvas.bind("<ButtonRelease-1>", self._onMouseButtonRelease1)
        self._shiftCanvas.bind("<B1-Motion>", self._onMouseButton1Motion)
        self._shiftCanvas.bind("<Double-Button-1>", self._onMouseDoubleButton1)

        self._shiftCanvas.bind("<Button-3>", self._onMouseButton3)
        #self._shiftCanvas.bind("<ButtonRelease-3>", self._onMouseButtonRelease3)
        self._shiftCanvas.bind("<B3-Motion>", self._onMouseButton3Motion)

        self._shiftCanvas.grid(row=0,column=1, padx=2, pady=2)
        self._shiftCanvas.create_oval(1, 1, 400, 400, outline="#ff0000")
        self._shiftCanvas.create_line(200, 2, 200, 400, fill="#ff0000")
        self._shiftCanvas.create_line(2, 200, 400, 200, fill="#ff0000")
        self._shiftMarker = self._shiftCanvas.create_oval(196, 196, 204, 204, outline="#0000ff", fill="#0000ff")
        
        self._yaw = DoubleVar()
        self._yawScale = Scale(controlFrame, orient=HORIZONTAL, from_=-100.0, to=100.0, \
                            tickinterval=0, variable=self._yaw, \
                            length=200, showvalue=1, \
                            command=self._onYawScaleChanged)
        self._yawScale.bind("<Double-Button-1>", self._onYawScaleDoubleButton1, "+")
        self._yawScale.grid(row=1, column=1)
        
        self._controlKeyActive = False
        

        #PID calibration

        pidCalibrationFrame = tkFrame(self)
        pidCalibrationFrame.grid(column=0, row=2, sticky="WE");

        self._pidSelected = StringVar()
        self._pidSelected.set("--")
        self._pidListBox = OptionMenu(pidCalibrationFrame, self._pidSelected, "--", \
                                      Cockpit.KEY_ANG_SPEED, Cockpit.KEY_ANGLES, Cockpit.KEY_ACCEL, \
                                       command=self._onPidListBoxChanged)
        self._pidListBox.pack(side=LEFT, padx=2)
        self._pidListBox.config(width=10)
        
        self._axisSelected = StringVar()
        self._axisSelected.set("--")
        self._axisListBox = OptionMenu(pidCalibrationFrame, self._axisSelected, "--", "X", "Y", "Z", \
                                       command=self._onAxisListBoxChanged)
        self._axisListBox.pack(side=LEFT, padx=2)
        self._axisListBox.config(state=DISABLED)

        Label(pidCalibrationFrame, text="P").pack(side=LEFT, padx=(14, 2))

        self._pidPString = StringVar()
        self._pidPString.set("0.00")
        self._pidPSpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \
                                         textvariable=self._pidPString, command=self._onPidSpinboxChanged)
        self._pidPSpinbox.pack(side=LEFT, padx=2)

        Label(pidCalibrationFrame, text="I").pack(side=LEFT, padx=(14, 2))

        self._pidIString = StringVar()
        self._pidIString.set("0.00")
        self._pidISpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \
                                         textvariable=self._pidIString, command=self._onPidSpinboxChanged)
        self._pidISpinbox.pack(side=LEFT, padx=2)
        
        Label(pidCalibrationFrame, text="D").pack(side=LEFT, padx=(14, 2))
        
        self._pidDString = StringVar()
        self._pidDString.set("0.00")
        self._pidDSpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \
                                         textvariable=self._pidDString, command=self._onPidSpinboxChanged)
        self._pidDSpinbox.pack(side=LEFT, padx=2)
        
        #debug
        debugFrame = tkFrame(self)
        debugFrame.grid(column=0, row=3, sticky="WE")
        
        self._debugMsg = Message(debugFrame, anchor="nw", justify=LEFT, relief=SUNKEN, width=300)
        self._debugMsg.pack(fill=BOTH, expand=1)
Ejemplo n.º 47
0
class GetCfgSectionNameDialog(Toplevel):
    def __init__(self, parent, title, message, used_names, _htest=False):
        """
        message - string, informational message to display
        used_names - string collection, names already in use for validity check
        _htest - bool, change box location when running htest
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        self.resizable(height=FALSE, width=FALSE)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self.Cancel)
        self.parent = parent
        self.message = message
        self.used_names = used_names
        self.create_widgets()
        self.withdraw()  #hide while setting geometry
        self.update_idletasks()
        #needs to be done here so that the winfo_reqwidth is valid
        self.messageInfo.config(width=self.frameMain.winfo_reqwidth())
        self.geometry("+%d+%d" %
                      (parent.winfo_rootx() +
                       (parent.winfo_width() / 2 - self.winfo_reqwidth() / 2),
                       parent.winfo_rooty() +
                       ((parent.winfo_height() / 2 -
                         self.winfo_reqheight() / 2) if not _htest else 100))
                      )  #centre dialog over parent (or below htest box)
        self.deiconify()  #geometry set, unhide
        self.wait_window()

    def create_widgets(self):
        self.name = StringVar(self.parent)
        self.fontSize = StringVar(self.parent)
        self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
        self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
        self.messageInfo = Message(self.frameMain,
                                   anchor=W,
                                   justify=LEFT,
                                   padx=5,
                                   pady=5,
                                   text=self.message)  #,aspect=200)
        entryName = Entry(self.frameMain, textvariable=self.name, width=30)
        entryName.focus_set()
        self.messageInfo.pack(padx=5, pady=5)  #, expand=TRUE, fill=BOTH)
        entryName.pack(padx=5, pady=5)
        frameButtons = Frame(self, pady=2)
        frameButtons.pack(side=BOTTOM)
        self.buttonOk = Button(frameButtons,
                               text='Ok',
                               width=8,
                               command=self.Ok)
        self.buttonOk.pack(side=LEFT, padx=5)
        self.buttonCancel = Button(frameButtons,
                                   text='Cancel',
                                   width=8,
                                   command=self.Cancel)
        self.buttonCancel.pack(side=RIGHT, padx=5)

    def name_ok(self):
        ''' After stripping entered name, check that it is a  sensible
        ConfigParser file section name. Return it if it is, '' if not.
        '''
        name = self.name.get().strip()
        if not name:  #no name specified
            tkMessageBox.showerror(title='Name Error',
                                   message='No name specified.',
                                   parent=self)
        elif len(name) > 30:  #name too long
            tkMessageBox.showerror(
                title='Name Error',
                message='Name too long. It should be no more than ' +
                '30 characters.',
                parent=self)
            name = ''
        elif name in self.used_names:
            tkMessageBox.showerror(title='Name Error',
                                   message='This name is already in use.',
                                   parent=self)
            name = ''
        return name

    def Ok(self, event=None):
        name = self.name_ok()
        if name:
            self.result = name
            self.destroy()

    def Cancel(self, event=None):
        self.result = ''
        self.destroy()
Ejemplo n.º 48
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
Ejemplo n.º 49
0
    def create_path(self):
        width_msg = 100
        width_path = 400

        path_frame = Frame(self.root)
        path_frame.pack(fill=X)
        # read
        read_frame = Frame(path_frame)
        read_frame.pack(fill=X)
        read_msg = Message(read_frame, width=width_msg, text='Video path:')
        read_msg.pack(side=LEFT)
        read_path = Message(read_frame, width=width_path, text='file1')
        read_path.pack(side=LEFT)
        read_btn = Button(read_frame, text="Choose file", command=self.click_read)
        read_btn.pack(side=RIGHT)
        # save
        save_frame = Frame(path_frame)
        save_frame.pack(fill=X)
        save_msg = Message(save_frame, width=width_msg, text='Save to:')
        save_msg.pack(side=LEFT)
        save_path = Message(save_frame, width=width_path, text='file2')
        save_path.pack(side=LEFT)
        save_btn = Button(save_frame, text="Choose file", command=self.click_save)
        save_btn.pack(side=RIGHT)

        self.read_path = read_path
        self.save_path = save_path
Ejemplo n.º 50
0
class GetCfgSectionNameDialog(Toplevel):
    def __init__(self, parent, title, message, used_names, _htest=False):
        """
        message - string, informational message to display
        used_names - string collection, names already in use for validity check
        _htest - bool, change box location when running htest
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        self.resizable(height=FALSE, width=FALSE)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self.Cancel)
        self.parent = parent
        self.message = message
        self.used_names = used_names
        self.create_widgets()
        self.withdraw()  #hide while setting geometry
        self.update_idletasks()
        #needs to be done here so that the winfo_reqwidth is valid
        self.messageInfo.config(width=self.frameMain.winfo_reqwidth())
        self.geometry(
                "+%d+%d" % (
                    parent.winfo_rootx() +
                    (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
                    parent.winfo_rooty() +
                    ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
                    if not _htest else 100)
                ) )  #centre dialog over parent (or below htest box)
        self.deiconify()  #geometry set, unhide
        self.wait_window()
    def create_widgets(self):
        self.name = StringVar(self.parent)
        self.fontSize = StringVar(self.parent)
        self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
        self.frameMain.pack(side=TOP, expand=TRUE, fill=BOTH)
        self.messageInfo = Message(self.frameMain, anchor=W, justify=LEFT,
                    padx=5, pady=5, text=self.message) #,aspect=200)
        entryName = Entry(self.frameMain, textvariable=self.name, width=30)
        entryName.focus_set()
        self.messageInfo.pack(padx=5, pady=5) #, expand=TRUE, fill=BOTH)
        entryName.pack(padx=5, pady=5)
        frameButtons = Frame(self, pady=2)
        frameButtons.pack(side=BOTTOM)
        self.buttonOk = Button(frameButtons, text='Ok',
                width=8, command=self.Ok)
        self.buttonOk.pack(side=LEFT, padx=5)
        self.buttonCancel = Button(frameButtons, text='Cancel',
                width=8, command=self.Cancel)
        self.buttonCancel.pack(side=RIGHT, padx=5)

    def name_ok(self):
        ''' After stripping entered name, check that it is a  sensible
        ConfigParser file section name. Return it if it is, '' if not.
        '''
        name = self.name.get().strip()
        if not name: #no name specified
            tkMessageBox.showerror(title='Name Error',
                    message='No name specified.', parent=self)
        elif len(name)>30: #name too long
            tkMessageBox.showerror(title='Name Error',
                    message='Name too long. It should be no more than '+
                    '30 characters.', parent=self)
            name = ''
        elif name in self.used_names:
            tkMessageBox.showerror(title='Name Error',
                    message='This name is already in use.', parent=self)
            name = ''
        return name
    def Ok(self, event=None):
        name = self.name_ok()
        if name:
            self.result = name
            self.destroy()
    def Cancel(self, event=None):
        self.result = ''
        self.destroy()
Ejemplo n.º 51
0
 def do_a_turn(self):
     # roll die
     die1_val = random.randint(1,6)
     die2_val = random.randint(1,6)
     # TODO: potentially simulate die motion like in matlab version
     # change die values on screen
     self.dice1_strvar.set(str(die1_val))
     self.dice2_strvar.set(str(die2_val))
     
     # check dice conditions
     ethan_val = int(self.ethan_strvar.get())
     player_val = int(self.player_strvars[self.player_turn].get())
     if (die1_val+die2_val == 4):
         # player gets ethan's stuff
         player_val = player_val + ethan_val
         ethan_val = 0
     elif (die1_val+die2_val == 2) and self.ethan_eyes:
         # player loses it all to ethan
         ethan_val = player_val + ethan_val
         player_val = 0
     else:
         # player loses one chip to ethan
         ethan_val = ethan_val + 1
         player_val = player_val - 1
     self.ethan_strvar.set(str(ethan_val))
     self.player_strvars[self.player_turn].set(str(player_val))
     # check for the lose condition
     total_chips = 0
     num_players_positive = 0
     for x in self.player_strvars:
         if int(x.get()) > 0:
             num_players_positive = num_players_positive + 1
         total_chips = total_chips + int(x.get())
     if total_chips == 0:
         # everybody loses
         error_dlg = Toplevel(master=self.main_window)
         error_dlg.geometry("%dx%d+%d+%d" % 
             (INIT_WINDOW_WIDTH, INIT_WINDOW_HEIGHT, X_POS, Y_POS))
         error_dlg.title( "LOSERS" );
         error_dlg.grab_set();
         error_msg = Message(error_dlg, aspect=300, text="EVERYBODY LOSES, AE2015")
         error_msg.pack();
         error_button = Button(error_dlg, text="OK", \
                             command=lambda: self.destroy_all(error_dlg));
         error_button.pack();
         error_dlg.update();
     elif (num_players_positive == 1) and (player_val > ethan_val):
         #win condition, only for player who just moved
         player_name = self.player_name_list[self.player_turn].get();
         error_dlg = Toplevel(master=self.main_window)
         error_dlg.geometry("%dx%d+%d+%d" % 
             (INIT_WINDOW_WIDTH, INIT_WINDOW_HEIGHT, X_POS, Y_POS))
         error_dlg.title( "WINNER" );
         error_dlg.grab_set();
         error_msg = Message(error_dlg, aspect=300, text="GOOD JOB %s, YOU BEAT ETHAN" % (player_name) )
         error_msg.pack();
         error_button = Button(error_dlg, text="OK", \
                                 command=error_dlg.destroy);
         error_button.pack();
         error_dlg.update();
     else:
         # game isn't over, increment turn to next positive player
         self.player_frame_list[self.player_turn].config(relief='flat', \
             borderwidth=0)
         num_players = len(self.player_strvars)
         found_next = 0
         self.current_turn = self.current_turn + 1
         while (found_next == 0):
             self.player_turn = (self.player_turn + 1) % num_players
             if int(self.player_strvars[self.player_turn].get()) > 0:
                 found_next = 1
         self.player_frame_list[self.player_turn].config(relief='raised', \
             borderwidth=2)    
     return
Ejemplo n.º 52
0
def vis_thread():
    global txt, color, txt2, color2

    def update():
        global txt, color, txt2, color2
        msg.config(text=txt, background=color)
        msg2.config(text=txt2, background=color2)
        root.after(250, update)

    root = Tk()
    root.geometry("900x600")

    msg = Message(root, text=txt, background=color)
    msg.config(font=('times', 200, 'italic bold'))
    msg.pack()

    msg2 = Message(root, text=txt2, background=color2)
    msg2.config(font=('times', 70, 'italic bold'))
    msg2.pack()

    root.after(250, update)

    root.mainloop()
runningPath = getScriptPath()
print "Script running at: " + runningPath

#Build Root UI Window
root1 = tk.Tk()
root1.iconbitmap('C:\Users\Landon\Desktop\Python Workspace\Steam-Library-Exporter\steambmp.ico')
root1.wm_title('Steam Library Exporter v0.9')
root1.tk_setPalette(background = "#FFFFFF", foreground = "black")

#Build Text & Entry Window Elements
packable_update = Label(root1, text = 'Ready!')

welcomeMessage = "Welcome to Steam Library Exporter!"
secondMessage = "This app gathers your entire Steam library from the web and all available stats within. \nIt even generates a handy Excel/Numbers spreadsheet for you!"
welcome1 = Message(root1, text=welcomeMessage, width=500, justify='center')
welcome2 = Message(root1, text=secondMessage, width=500, justify='center')

label = tk.Label(root1, text='Enter your Steam Login ID: ')
entry = tk.Entry(root1)
entry.focus_set()

#Image UI
steamLogo = ImageTk.PhotoImage(Image.open('C:\Users\Landon\Desktop\Python Workspace\Steam-Library-Exporter\steamExporterBanner.png'))
panel = tk.Label(root1, image = steamLogo)

"------------------------------------- MAIN METHOD -------------------------------------"
def mainMethod():

    #Message: To Display After User Enters Steam Username
    update_the_label('Searching...')
Ejemplo n.º 54
0
    def initUI(self):
        self.parent.title("Client")
        frame = Frame(self, relief=tk.RAISED, borderwidth=1)

        # The width of the first column gets almost no change.
        frame.columnconfigure(0, pad=10, weight=1)
        frame.columnconfigure(1, pad=10, weight=1000)

        lbl_addr = Label(frame, text="Address")
        lbl_addr.grid(row=0,column=0, sticky=tk.W+tk.S)

        lbl_port = Label(frame, text="Port")
        lbl_port.grid(row=0,column=1, sticky=tk.W+tk.S)

        ent_addr = Entry(frame, width=15)
        ent_addr.grid(row=1,column=0, sticky=tk.W+tk.N)

        ent_port = Entry(frame, width=6)
        ent_port.grid(row=1,column=1, sticky=tk.W+tk.N)

        lbl_msg = Label(frame, text="Input Message", anchor=tk.E)
        lbl_msg.grid(row=2,column=0, sticky=tk.W+tk.S)

        ent_msg = Text(frame, width=30, height=4)
        ent_msg.grid(row=3,column=0, columnspan=2, sticky=tk.W+tk.E+tk.N) # sticky can be used to expand

        lbl_num = Label(frame, text="Input Number")
        lbl_num.grid(row=4,column=0, sticky=tk.W+tk.S)

        ent_num = Entry(frame, width=6)
        ent_num.grid(row=5,column=0, sticky=tk.W+tk.N)
        # ======================

        ret_indicator = tk.StringVar()
        ret_indicator.set("Result")
        lab_res = Label(frame, textvariable=ret_indicator)
        lab_res.grid(row=6,column=0, sticky=tk.W+tk.S)

        var_res = tk.StringVar()
        msg_res = Message(frame,textvariable=var_res, width=500)
        msg_res.grid(row=7,column=0, columnspan=2,sticky=tk.W+tk.E+tk.N)

        frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        def connect():
            self.addr = ent_addr.get()
            portStr = ent_port.get()

            if self.addr == "":
                self.addr = "localhost"

            if portStr == "":
                self.port = 50000
            else:
                self.port = int(portStr)

            (ret, info) = ec.connect(self.addr, self.port)
            if ret == 0:
                ret_indicator.set("Connection Succeeded")
                self.conn = info
                var_res.set("")
            else:
                ret_indicator.set("Connection Failed")
                var_res.set(info)

        def sendMsg():
            msg = ent_msg.get("0.0", tk.END)[0:-1]
            print "msg to be sent is: " + repr(msg)
            (ret, info) = ec.sendMsg(self.conn, msg.encode('utf-8'))
            if ret == 0:
                ret_indicator.set("Send Succeeded")
                var_res.set("")
            else:
                ret_indicator.set("Send Failed")
                var_res.set(info)

        def sendNum():
            msg = ent_num.get()
            print "msg to be sent is: " + repr(msg)
            (ret, info) = ec.sendNum(self.conn, int(msg))
            if ret == 0:
                ret_indicator.set("Send Succeeded")
                var_res.set("")
            else:
                ret_indicator.set("Send Failed")
                var_res.set(info)

        def recvMsg():
            (ret, info) = ec.recvMsg(self.conn)
            if ret == 0:
                ret_indicator.set("Receive Succeeded")
            else:
                ret_indicator.set("Receive Failed")
            var_res.set(info)

        def close():
            (ret, info) = ec.close(self.conn)
            if ret == 0:
                ret_indicator.set("Close Succeeded")
                var_res.set("")
            else:
                ret_indicator.set("Close Failed")
                var_res.set(info)

        frame2 = Frame(self, relief=tk.RAISED, borderwidth=1)

        """Buttoms are always in the middle."""
        frame2.columnconfigure(0, pad=10, weight=1)
        frame2.rowconfigure(0, weight=1000)
        frame2.rowconfigure(1, weight=1)
        frame2.rowconfigure(2, weight=1)
        frame2.rowconfigure(3, weight=1)
        frame2.rowconfigure(4, weight=1)
        frame2.rowconfigure(5, weight=1)
        frame2.rowconfigure(6, weight=1000)

        but_conn = Button(frame2, text="Connect", command=connect)
        but_conn.grid(row=1,column=0, sticky=tk.W+tk.E)

        but_send_msg = Button(frame2, text="Send Message", command=sendMsg)
        but_send_msg.grid(row=2,column=0, sticky=tk.W+tk.E)

        but_send_num = Button(frame2, text="Send Number", command=sendNum)
        but_send_num.grid(row=3,column=0, sticky=tk.W+tk.E)

        but_recv = Button(frame2, text="Receive", command=recvMsg)
        but_recv.grid(row=4,column=0, sticky=tk.W+tk.E)

        but_close = Button(frame2, text="Close", command=close)
        but_close.grid(row=5,column=0, sticky=tk.W+tk.E)

        frame2.pack(side=tk.LEFT, fill=tk.BOTH,expand=1)

        # expand=1 cannot be omitted
        self.pack(fill=tk.BOTH, expand=1)
Ejemplo n.º 55
0
    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)
Ejemplo n.º 56
0
class Cockpit(ttkFrame):
    '''
    Remote device GUI 
    '''
    
    #TODO: 20160415 DPM - Set these values from configuration file
    #--- config
    THROTTLE_BY_USER = True
    THROTTLE_RESOLUTION = 0.1
    
    # Joystick enabled or not, if any
    JOYSTICK_ENABLED = True 

    DEFAULT_DRONE_IP = "192.168.1.130"
    DEFAULT_DRONE_PORT = 2121
    #--- end config
    

    KEY_ANG_SPEED = "ang-speed"
    KEY_ANGLES = "angles"
    KEY_ACCEL = "accel"
    
    PID_KEYS = ["P", "I", "D"]

    DIR_NONE = 0
    DIR_VERTICAL = 1
    DIR_HORIZONTAL = 2
    
    def __init__(self, parent, isDummy = False, droneIp = DEFAULT_DRONE_IP, dronePort = DEFAULT_DRONE_PORT):
        '''
        Constructor
        '''
        ttkFrame.__init__(self, parent)
        
        self._target = [0.0] * 4        
        
        self._selectedPidConstats = "--"
        self._pidConstants = {
                              Cockpit.KEY_ANG_SPEED:{
                                           "X":{
                                                "P": 0.0,
                                                "I": 0.0,
                                                "D": 0.0
                                                },
                                           "Y":{
                                                "P": 0.0,
                                                "I": 0.0,
                                                "D": 0.0
                                                },
                                           "Z":{
                                                "P": 0.0,
                                                "I": 0.0,
                                                "D": 0.0
                                                }
                                           },
                               Cockpit.KEY_ANGLES: {
                                          "X":{
                                                "P": 0.0,
                                                "I": 0.0,
                                                "D": 0.0
                                                },
                                           "Y":{
                                                "P": 0.0,
                                                "I": 0.0,
                                                "D": 0.0
                                                }
                                          },
                               Cockpit.KEY_ACCEL:{
                                           "X":{
                                                "P": 0.0,
                                                "I": 0.0,
                                                "D": 0.0
                                                },
                                           "Y":{
                                                "P": 0.0,
                                                "I": 0.0,
                                                "D": 0.0
                                                },
                                            "Z":{
                                                "P": 0.0,
                                                "I": 0.0,
                                                "D": 0.0
                                                 }
                                          }
                              }
        
        self.parent = parent

        self.initUI()

        self._controlKeysLocked = False

        if not isDummy:
            self._link = INetLink(droneIp, dronePort)
        else:
            self._link = ConsoleLink()
            
        self._link.open()

        self._updateInfoThread = Thread(target=self._updateInfo)
        self._updateInfoThreadRunning = False
        self._readingState = False

        self._start()
        
            
    def initUI(self):
        
        self.parent.title("Drone control")
        self.style = Style()
        self.style.theme_use("default")
        
        self.pack(fill=BOTH, expand=1)
        
        self.parent.bind_all("<Key>", self._keyDown)
        self.parent.bind_all("<KeyRelease>", self._keyUp)

        if system() == "Linux":
            self.parent.bind_all("<Button-4>", self._onMouseWheelUp)
            self.parent.bind_all("<Button-5>", self._onMouseWheelDown)

        else:
            #case of Windows
            self.parent.bind_all("<MouseWheel>", self._onMouseWheel)
        
        #Commands        
        commandsFrame = tkFrame(self)
        commandsFrame.grid(column=0, row=0, sticky="WE")
        
        self._started = IntVar()
        self._startedCB = Checkbutton(commandsFrame, text="On", variable=self._started, command=self._startedCBChanged)
        self._startedCB.pack(side=LEFT, padx=4)
        
#         self._integralsCB = Checkbutton(commandsFrame, text="Int.", variable=self._integralsEnabled, \
#                                         command=self._integralsCBChanged, state=DISABLED)
#         self._integralsCB.pack(side=LEFT, padx=4)
        
        self._quitButton = Button(commandsFrame, text="Quit", command=self.exit)
        self._quitButton.pack(side=LEFT, padx=2, pady=2)
        
#         self._angleLbl = Label(commandsFrame, text="Angle")
#         self._angleLbl.pack(side=LEFT, padx=4)
#         
#         self._angleEntry = Entry(commandsFrame, state=DISABLED)
#         self._angleEntry.pack(side=LEFT)
        
        #Info
        infoFrame = tkFrame(self)
        infoFrame.grid(column=1, row=1, sticky="NE", padx=4)
        
        #Throttle
        Label(infoFrame, text="Throttle").grid(column=0, row=0, sticky="WE")        
        self._throttleTexts = [StringVar(),StringVar(),StringVar(),StringVar()]
        Entry(infoFrame, textvariable=self._throttleTexts[3], state=DISABLED, width=5).grid(column=0, row=1)                
        Entry(infoFrame, textvariable=self._throttleTexts[0], state=DISABLED, width=5).grid(column=1, row=1)
        Entry(infoFrame, textvariable=self._throttleTexts[2], state=DISABLED, width=5).grid(column=0, row=2)
        Entry(infoFrame, textvariable=self._throttleTexts[1], state=DISABLED, width=5).grid(column=1, row=2)
        
        #Angles
        Label(infoFrame, text="Angles").grid(column=0, row=3, sticky="WE")        
        self._angleTexts = [StringVar(),StringVar(),StringVar()]
        for index in range(3):
            Entry(infoFrame, textvariable=self._angleTexts[index], state=DISABLED, width=5).grid(column=index, row=4)
               
        #Accels
        Label(infoFrame, text="Accels").grid(column=0, row=5, sticky="WE")
        self._accelTexts = [StringVar(),StringVar(),StringVar()]
        for index in range(3):
            Entry(infoFrame, textvariable=self._accelTexts[index], state=DISABLED, width=5).grid(column=index, row=6)
        
        #Speeds
        Label(infoFrame, text="Speeds").grid(column=0, row=7, sticky="WE")
        self._speedTexts = [StringVar(),StringVar(),StringVar()]
        for index in range(3):
            Entry(infoFrame, textvariable=self._speedTexts[index], state=DISABLED, width=5).grid(column=index, row=8)
        
        #Height
        Label(infoFrame, text="Height").grid(column=0, row=9, sticky="E")
        self._heightText = StringVar()
        Entry(infoFrame, textvariable=self._heightText, state=DISABLED, width=5).grid(column=1, row=9)
        
        #Loop rate
        Label(infoFrame, text="Loop @").grid(column=0, row=10, sticky="E")
        self._loopRateText = StringVar()
        Entry(infoFrame, textvariable=self._loopRateText, state=DISABLED, width=5).grid(column=1, row=10)
        Label(infoFrame, text="Hz").grid(column=2, row=10, sticky="W")
        
        #control
        
        controlFrame = tkFrame(self)
        controlFrame.grid(column=0, row=1, sticky="W")
        
        self._throttle = DoubleVar()
        
        if Cockpit.THROTTLE_BY_USER:

            self._thrustScale = Scale(controlFrame, orient=VERTICAL, from_=100.0, to=0.0, \
                                tickinterval=0, variable=self._throttle, resolution=Cockpit.THROTTLE_RESOLUTION, \
                                length=200, showvalue=1, \
                                state=DISABLED,
                                command=self._onThrustScaleChanged)

        else:
        
            self._thrustScale = Scale(controlFrame, orient=VERTICAL, from_=100.0, to=-100.0, \
                                tickinterval=0, variable=self._throttle, \
                                length=200, showvalue=1, \
                                state=DISABLED,
                                command=self._onThrustScaleChanged)

        self._thrustScale.bind("<Double-Button-1>", self._onThrustScaleDoubleButton1, "+")
        self._thrustScale.grid(column=0)
        
        self._shiftCanvas = Canvas(controlFrame, bg="white", height=400, width=400, \
                             relief=SUNKEN)
        self._shiftCanvas.bind("<Button-1>", self._onMouseButton1)
        #self._shiftCanvas.bind("<ButtonRelease-1>", self._onMouseButtonRelease1)
        self._shiftCanvas.bind("<B1-Motion>", self._onMouseButton1Motion)
        self._shiftCanvas.bind("<Double-Button-1>", self._onMouseDoubleButton1)

        self._shiftCanvas.bind("<Button-3>", self._onMouseButton3)
        #self._shiftCanvas.bind("<ButtonRelease-3>", self._onMouseButtonRelease3)
        self._shiftCanvas.bind("<B3-Motion>", self._onMouseButton3Motion)

        self._shiftCanvas.grid(row=0,column=1, padx=2, pady=2)
        self._shiftCanvas.create_oval(1, 1, 400, 400, outline="#ff0000")
        self._shiftCanvas.create_line(200, 2, 200, 400, fill="#ff0000")
        self._shiftCanvas.create_line(2, 200, 400, 200, fill="#ff0000")
        self._shiftMarker = self._shiftCanvas.create_oval(196, 196, 204, 204, outline="#0000ff", fill="#0000ff")
        
        self._yaw = DoubleVar()
        self._yawScale = Scale(controlFrame, orient=HORIZONTAL, from_=-100.0, to=100.0, \
                            tickinterval=0, variable=self._yaw, \
                            length=200, showvalue=1, \
                            command=self._onYawScaleChanged)
        self._yawScale.bind("<Double-Button-1>", self._onYawScaleDoubleButton1, "+")
        self._yawScale.grid(row=1, column=1)
        
        self._controlKeyActive = False
        

        #PID calibration

        pidCalibrationFrame = tkFrame(self)
        pidCalibrationFrame.grid(column=0, row=2, sticky="WE");

        self._pidSelected = StringVar()
        self._pidSelected.set("--")
        self._pidListBox = OptionMenu(pidCalibrationFrame, self._pidSelected, "--", \
                                      Cockpit.KEY_ANG_SPEED, Cockpit.KEY_ANGLES, Cockpit.KEY_ACCEL, \
                                       command=self._onPidListBoxChanged)
        self._pidListBox.pack(side=LEFT, padx=2)
        self._pidListBox.config(width=10)
        
        self._axisSelected = StringVar()
        self._axisSelected.set("--")
        self._axisListBox = OptionMenu(pidCalibrationFrame, self._axisSelected, "--", "X", "Y", "Z", \
                                       command=self._onAxisListBoxChanged)
        self._axisListBox.pack(side=LEFT, padx=2)
        self._axisListBox.config(state=DISABLED)

        Label(pidCalibrationFrame, text="P").pack(side=LEFT, padx=(14, 2))

        self._pidPString = StringVar()
        self._pidPString.set("0.00")
        self._pidPSpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \
                                         textvariable=self._pidPString, command=self._onPidSpinboxChanged)
        self._pidPSpinbox.pack(side=LEFT, padx=2)

        Label(pidCalibrationFrame, text="I").pack(side=LEFT, padx=(14, 2))

        self._pidIString = StringVar()
        self._pidIString.set("0.00")
        self._pidISpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \
                                         textvariable=self._pidIString, command=self._onPidSpinboxChanged)
        self._pidISpinbox.pack(side=LEFT, padx=2)
        
        Label(pidCalibrationFrame, text="D").pack(side=LEFT, padx=(14, 2))
        
        self._pidDString = StringVar()
        self._pidDString.set("0.00")
        self._pidDSpinbox = Spinbox(pidCalibrationFrame, width=5, from_=0.0, to=10000.0, increment=0.01, state=DISABLED, \
                                         textvariable=self._pidDString, command=self._onPidSpinboxChanged)
        self._pidDSpinbox.pack(side=LEFT, padx=2)
        
        #debug
        debugFrame = tkFrame(self)
        debugFrame.grid(column=0, row=3, sticky="WE")
        
        self._debugMsg = Message(debugFrame, anchor="nw", justify=LEFT, relief=SUNKEN, width=300)
        self._debugMsg.pack(fill=BOTH, expand=1)



    def _start(self):

        self._readDroneConfig()
        
        if Cockpit.JOYSTICK_ENABLED:
            self._joystickManager = JoystickManager.getInstance()
            self._joystickManager.start()
            
            joysticks = self._joystickManager.getJoysticks()
            if len(joysticks) != 0:
                self._joystick = joysticks[0]
                self._joystick.onAxisChanged += self._onJoystickAxisChanged
                self._joystick.onButtonPressed += self._onJoystickButtonPressed
            else:
                self._joystick = None     
        
        
    def _onJoystickAxisChanged(self, sender, index):
        
        if self._started.get() and sender == self._joystick:
            
            axisValue = self._joystick.getAxisValue(index) 
            
            if index == 0:
                
                self._yaw.set(axisValue)
                self._updateTarget()
            
            elif index == 1 and not Cockpit.THROTTLE_BY_USER:
            
                thrust = -axisValue
                self._throttle.set(thrust)            
                self._updateTarget()

            elif index == 2 and Cockpit.THROTTLE_BY_USER:            
            
                rowThrottle = (axisValue + 100.0)/2.0 
                if rowThrottle < 10.0:
                    throttle = rowThrottle * 6.0
                elif rowThrottle < 90.0:
                    throttle = 60.0 + ((rowThrottle - 10.0) / 8.0)
                else:
                    throttle = 70.0 + (rowThrottle - 90.0) * 3.0
                self._throttle.set(throttle)
                self._sendThrottle()
                
            elif index == 3:
                
                x = 196 + axisValue * 2                
                lastCoords = self._shiftCanvas.coords(self._shiftMarker)
                coords = (x, lastCoords[1])                 
                self._plotShiftCanvasMarker(coords)
                
            elif index == 4:
                
                y = 196 + axisValue * 2 
                lastCoords = self._shiftCanvas.coords(self._shiftMarker)
                coords = (lastCoords[0], y)                 
                self._plotShiftCanvasMarker(coords)


    def _onJoystickButtonPressed(self, sender, index):
        
        if sender == self._joystick and index == 7:
            
            if self._started.get() == 0:
                self._startedCB.select()
            else:
                self._startedCB.deselect()
                
            # Tkinter's widgets seem not to be calling the event-handler
            # when they are changed programmatically. Therefore, the 
            # even-handler is called explicitly here.
            self._startedCBChanged()
        
    
    def exit(self):
        
        self._link.send({"key": "close", "data": None})
        
        self._stopUpdateInfoThread()
        
        self._link.close()

        if Cockpit.JOYSTICK_ENABLED:
            self._joystickManager.stop()
        
        self.quit()


    def _updateTarget(self):
        
        markerCoords = self._shiftCanvas.coords(self._shiftMarker)
        coords = ((markerCoords[0] + markerCoords[2]) / 2, (markerCoords[1] + markerCoords[3]) / 2)
        
        self._target[0] = float(coords[1] - 200) / 2.0 # X-axis angle / X-axis acceleration
        self._target[1] = float(coords[0] - 200) / 2.0 # Y-axis angle / Y-axis acceleration
        #Remote control uses clockwise angle, but the drone's referece system uses counter-clockwise angle
        self._target[2] = -self._yaw.get() # Z-axis angular speed
        
        # Z-axis acceleration (thrust). Only when the motor throttle is not controlled by user directly
        if Cockpit.THROTTLE_BY_USER:
            self._target[3] = 0.0
        else:        
            self._target[3] = self._throttle.get()
        
        self._sendTarget() 
    
        
    def _keyDown(self, event):

        if event.keysym == "Escape":            
            self._throttle.set(0)
            self._started.set(0)
            self._thrustScale.config(state=DISABLED)
            self._stopUpdateInfoThread()
            self._sendIsStarted()
            
        elif event.keysym.startswith("Control"):            
            self._controlKeyActive = True
            
        elif not self._controlKeysLocked and self._controlKeyActive:
            
            if event.keysym == "Up":
                self._thrustScaleUp()
                
            elif event.keysym == "Down":
                self._thrustScaleDown()
                
            elif event.keysym == "Left":
                self._yawLeft()
                
            elif event.keysym == "Right":
                self._yawRight()
                
            elif event.keysym == "space":
                self._yawReset()
                if not Cockpit.THROTTLE_BY_USER:
                    self._thrustReset()
                
        elif not self._controlKeysLocked and not self._controlKeyActive:
            
            if event.keysym == "Up":
                self._moveShiftCanvasMarker((0,-5))
                
            elif event.keysym == "Down":
                self._moveShiftCanvasMarker((0,5))
                
            elif event.keysym == "Left":
                self._moveShiftCanvasMarker((-5,0))
                
            elif event.keysym == "Right":
                self._moveShiftCanvasMarker((5,0))
                
            elif event.keysym == "space":
                self._resetShiftCanvasMarker()                
    
    
    def _keyUp(self, eventArgs):
        
        if eventArgs.keysym.startswith("Control"):
            self._controlKeyActive = False
            
    
    def _onMouseButton1(self, eventArgs):

        self._lastMouseCoords = (eventArgs.x, eventArgs.y)

        
    def _onMouseButtonRelease1(self, eventArgs):

        self._shiftCanvas.coords(self._shiftMarker, 196, 196, 204, 204)

    
    def _limitCoordsToSize(self, coords, size, width):
        
        maxSize = size-(width/2.0)
        minSize = -(width/2.0)
        
        if coords[0] > maxSize:
            x = maxSize
        
        elif coords[0] < minSize:
            x = minSize
            
        else:
            x = coords[0]
            
            
        if coords[1] > maxSize:
            y = maxSize
            
        elif coords[1] < minSize:
            y = minSize
            
        else:
            y = coords[1]
            
        
        return (x,y)
    
    
    def _plotShiftCanvasMarker(self, coords):
        
        coords = self._limitCoordsToSize(coords, 400, 8)
        self._shiftCanvas.coords(self._shiftMarker, coords[0], coords[1], coords[0] + 8, coords[1] + 8)
        self._updateTarget()

    
    def _moveShiftCanvasMarker(self, shift):

        lastCoords = self._shiftCanvas.coords(self._shiftMarker)
        newCoords = (lastCoords[0] + shift[0], lastCoords[1] + shift[1])        
        self._plotShiftCanvasMarker(newCoords)
    
    
    def _resetShiftCanvasMarker(self):
    
        self._shiftCanvas.coords(self._shiftMarker, 196, 196, 204, 204)
        self._updateTarget()
        
    
    def _onMouseButton1Motion(self, eventArgs):

        deltaCoords = (eventArgs.x - self._lastMouseCoords[0], eventArgs.y - self._lastMouseCoords[1])
        self._moveShiftCanvasMarker(deltaCoords)
        self._lastMouseCoords = (eventArgs.x, eventArgs.y)
  
      
    def _onMouseDoubleButton1(self, eventArgs):
        
        self._resetShiftCanvasMarker()        
            

    def _onMouseButton3(self, eventArgs):

        self._lastMouseCoords = (eventArgs.x, eventArgs.y)
        self._mouseDirection = Cockpit.DIR_NONE

        
    def _onMouseButtonRelease3(self, eventArgs):

        self._shiftCanvas.coords(self._shiftMarker, 196, 196, 204, 204)

        
    def _onMouseButton3Motion(self, eventArgs):

        deltaCoords = (eventArgs.x - self._lastMouseCoords[0], eventArgs.y - self._lastMouseCoords[1])

        if self._mouseDirection == Cockpit.DIR_NONE:
            if abs(deltaCoords[0]) > abs(deltaCoords[1]):
                self._mouseDirection = Cockpit.DIR_HORIZONTAL
            else:
                self._mouseDirection = Cockpit.DIR_VERTICAL

        if self._mouseDirection == Cockpit.DIR_HORIZONTAL:
            deltaCoords = (deltaCoords[0], 0)
        else:
            deltaCoords = (0, deltaCoords[1])

        self._moveShiftCanvasMarker(deltaCoords)
        self._lastMouseCoords = (eventArgs.x, eventArgs.y)
        
    
    def _thrustScaleUp(self):

        #TODO: 20160526 DPM: El valor de incremento de aceleración (1.0) puede ser muy alto
        if self._started.get(): 
            newValue = self._thrustScale.get() \
                + (Cockpit.THROTTLE_RESOLUTION if Cockpit.THROTTLE_BY_USER else 1.0)
            self._thrustScale.set(newValue)
            
            self._updateTarget()
    
    
    def _thrustScaleDown(self):
        
        #TODO: 20160526 DPM: El valor de decremento de aceleración (1.0) puede ser muy alto
        if self._started.get():
            newValue = self._thrustScale.get() \
                - (Cockpit.THROTTLE_RESOLUTION if Cockpit.THROTTLE_BY_USER else 1.0)
            self._thrustScale.set(newValue)
            
            self._updateTarget()
            
    
    def _thrustReset(self):
        
        if self._started.get():
            self._thrustScale.set(0.0)
            
            self._updateTarget()
            
            
    def _onThrustScaleDoubleButton1(self, eventArgs):
        
        self._thrustReset()
        
        return "break"
        
    
    def _yawRight(self):
        
        newValue = self._yaw.get() + 1
        self._yaw.set(newValue)
        self._updateTarget()
            

    def _yawLeft(self):
        
        newValue = self._yaw.get() - 1
        self._yaw.set(newValue)
        self._updateTarget()
        
        
    def _yawReset(self):
        
        self._yaw.set(0)
        self._updateTarget()
        
        
    def _onMouseWheelUp(self, eventArgs):
        
        if not self._controlKeyActive:
            self._thrustScaleUp()
            
        else:
            self._yawRight()
            

    def _onMouseWheelDown(self, eventArgs):

        if not self._controlKeyActive:
            self._thrustScaleDown()
            
        else:
            self._yawLeft()
    

    def _onMouseWheel(self, eventArgs):

        factor = eventArgs.delta/(1200.0 if Cockpit.THROTTLE_BY_USER and not self._controlKeyActive else 120.0)

        if not self._controlKeyActive:
        
            if self._started.get():
                newValue = self._thrustScale.get() + factor 
                self._thrustScale.set(newValue)
                
                self._updateTarget()
        else:
            newValue = self._yaw.get() + factor
            self._yaw.set(newValue)
            self._updateTarget()

    
    def _onYawScaleChanged(self, eventArgs):
        
        self._updateTarget()
    
    
    def _onYawScaleDoubleButton1(self, eventArgs):
        
        self._yawReset()
        
        return "break"
        
    
    def _startedCBChanged(self):
        
        if not self._started.get():
            self._throttle.set(0)
            self._thrustScale.config(state=DISABLED)            
            #self._integralsCB.config(state=DISABLED)
            self._stopUpdateInfoThread()
        else:
            self._thrustScale.config(state="normal")            
            #self._integralsCB.config(state="normal")
            self._startUpdateInfoThread()
            
        self._sendIsStarted()
     
    
#     def _integralsCBChanged(self):
#     
#         self._link.send({"key": "integrals", "data":self._integralsEnabled.get() != 0})
#             
    
     
    def _onThrustScaleChanged(self, eventArgs):
        
        if Cockpit.THROTTLE_BY_USER:
            
            self._sendThrottle()
        
        else:
        
            self._updateTarget()


    def _sendThrottle(self):
        
        self._link.send({"key": "throttle", "data": self._throttle.get()})
    

    def _sendTarget(self):
        
        self._link.send({"key": "target", "data": self._target})
        
        
    def _sendIsStarted(self):
        
        isStarted = self._started.get() != 0        
        self._link.send({"key": "is-started", "data": isStarted})
        

    def _sendPidCalibrationData(self):

        if self._pidSelected.get() != "--" and self._axisSelected.get() != "--":

            pidData = {
                "pid": self._pidSelected.get(),
                "axis": self._axisSelected.get(), 
                "p": float(self._pidPSpinbox.get()),
                "i": float(self._pidISpinbox.get()),
                "d": float(self._pidDSpinbox.get())}
        
            self._link.send({"key": "pid-calibration", "data": pidData})


    def _updatePidCalibrationData(self):

        pid = self._pidSelected.get()
        axis = self._axisSelected.get()

        if pid != "--" and axis != "--":
             
            self._pidConstants[pid][axis]["P"] = float(self._pidPSpinbox.get())
            self._pidConstants[pid][axis]["I"] = float(self._pidISpinbox.get())
            self._pidConstants[pid][axis]["D"] = float(self._pidDSpinbox.get())
            

    def _readDroneConfig(self):

        self._link.send({"key": "read-drone-config", "data": None}, self._onDroneConfigRead)


    def _readDroneState(self):
        
        if not self._readingState:
            self._readingState = True
            self._link.send({"key": "read-drone-state", "data": None}, self._onDroneStateRead)


    def _readPidConfigItem(self, message, cockpitKey, axises, configKeys):
        
        for i in range(len(axises)):
            for j in range(len(Cockpit.PID_KEYS)):
                self._pidConstants[cockpitKey][axises[i]][Cockpit.PID_KEYS[j]] = message[configKeys[j]][i]
                

    def _onDroneConfigRead(self, message):

        #TODO Show current configuration within the GUI (at least relevant settings)
        if message:
            
            #Angle-speeds
            self._readPidConfigItem(message, Cockpit.KEY_ANG_SPEED, ["X", "Y", "Z"], \
                                    [Configuration.PID_ANGLES_SPEED_KP, \
                                     Configuration.PID_ANGLES_SPEED_KI, \
                                     Configuration.PID_ANGLES_SPEED_KD])
            
            #Angles
            self._readPidConfigItem(message, Cockpit.KEY_ANGLES, ["X", "Y"], \
                                    [Configuration.PID_ANGLES_KP, \
                                     Configuration.PID_ANGLES_KI, \
                                     Configuration.PID_ANGLES_KD])
                        
            #Accels
            self._readPidConfigItem(message, Cockpit.KEY_ACCEL, ["X", "Y", "Z"], \
                                    [Configuration.PID_ACCEL_KP, \
                                     Configuration.PID_ACCEL_KI, \
                                     Configuration.PID_ACCEL_KD])
        

    def _onDroneStateRead(self, state):
        
        if state:
            
            for index in range(4):
                self._throttleTexts[index].set("{0:.3f}".format(state["_throttles"][index]))
                
            for index in range(3):
                self._accelTexts[index].set("{0:.3f}".format(state["_accels"][index]))
                self._angleTexts[index].set("{0:.3f}".format(state["_angles"][index]))
                
            currentPeriod = state["_currentPeriod"]
            if currentPeriod > 0.0:
                
                freq = 1.0/currentPeriod                
                self._loopRateText.set("{0:.3f}".format(freq))
                
            else:
                self._loopRateText.set("--")
                
        else:
            self._stopUpdateInfoThread()
            
        self._readingState = False
   

    def _onPidSpinboxChanged(self):

        self._updatePidCalibrationData()
        self._sendPidCalibrationData()

    
    def _onPidListBoxChanged(self, pid):
        
        self._axisSelected.set("--")
        
        self._pidPString.set("--")
        self._pidIString.set("--")
        self._pidDString.set("--")

        self._pidPSpinbox.config(state=DISABLED)
        self._pidISpinbox.config(state=DISABLED)
        self._pidDSpinbox.config(state=DISABLED)

        self._selectedPidConstats = pid

        if pid == "--":
            self._axisListBox.config(state=DISABLED)
            self._controlKeysLocked = False
                       
        else:
            self._axisListBox.config(state="normal")
            self._controlKeysLocked = True


    def _onAxisListBoxChanged(self, axis):
        
        if axis == "--" or (self._selectedPidConstats == Cockpit.KEY_ANGLES and axis == "Z"):
            
            self._pidPString.set("--")
            self._pidIString.set("--")
            self._pidDString.set("--")
            
            self._pidPSpinbox.config(state=DISABLED)
            self._pidISpinbox.config(state=DISABLED)
            self._pidDSpinbox.config(state=DISABLED)
            
            self._controlKeysLocked = axis != "--"
            
        else:
            
            self._pidPString.set("{:.2f}".format(self._pidConstants[self._selectedPidConstats][axis]["P"]))
            self._pidIString.set("{:.2f}".format(self._pidConstants[self._selectedPidConstats][axis]["I"]))
            self._pidDString.set("{:.2f}".format(self._pidConstants[self._selectedPidConstats][axis]["D"]))
            
            self._pidPSpinbox.config(state="normal")
            self._pidISpinbox.config(state="normal")
            self._pidDSpinbox.config(state="normal")
            
            self._controlKeysLocked = True

            
    def _updateInfo(self):
        
        while self._updateInfoThreadRunning:
            
            self._readDroneState()
            
            time.sleep(1.0)
            

    def _startUpdateInfoThread(self):
        
        self._updateInfoThreadRunning = True
        if not self._updateInfoThread.isAlive():                
            self._updateInfoThread.start()
        
            
    def _stopUpdateInfoThread(self):
        
        self._updateInfoThreadRunning = False
        if self._updateInfoThread.isAlive():
            self._updateInfoThread.join()
Ejemplo n.º 57
0
def smallentryframetextv(f,r,c,v,w,t,p=0):
    e = smallentry(f,v,w)
    m = Message(f,text=t, bg=Styles.colours["grey"],width=100)
    m.grid(row=r,column=c,padx=p,sticky=W)
    e.grid(row=r+1,column=c,sticky=W,padx=3)
    return (m,e)
Ejemplo n.º 58
0
        root = Tk();
        init_main_window(root, ethan_eyes);
        app = Ethan(root, player_num, ethan_eyes);
        root.mainloop();
    return
    
#start program with dialog box, which will lead to either just terminating
#or making a game box
if __name__ == "__main__":
    player_dlg = Tk();
    player_dlg.geometry("%dx%d+%d+%d" % 
        (INIT_WINDOW_WIDTH, INIT_WINDOW_HEIGHT, X_POS, Y_POS))
    # TODO: make dialog box show up in the middle of the screen based on
    # screen resolution
    player_dlg.title("How many players?")
    msg = Message(player_dlg, text="How many players will be playing this time?");
    msg.pack()
    player_count = Entry(player_dlg)
    player_count.pack()
    ethan_eyes_var = IntVar()
    ethan_eyes_check = Checkbutton(player_dlg, \
                                   text="enable Ethan Eyes", \
                                   var=ethan_eyes_var)
    ethan_eyes_check.pack()
    confirm_button = Button(player_dlg, text="OK", \
                            command=lambda: generate_main(player_dlg, \
                                                          player_count, \
                                                          ethan_eyes_var) );
    confirm_button.pack();
    cancle_button = Button(player_dlg, text="Cancel", \
                            command=lambda: player_dlg.quit() );
Ejemplo n.º 59
0
                           to=200,
                           orient=HORIZONTAL,
                           length=170,
                           width=10,
                           variable=LepTmassMax_val,
                           bg="lavender",
                           label="Maximum transverse mass")

emptyf2 = Frame(OptionsLep, width="170")  #just to mantain OptionsLep width

#Question mark to be next to "invariant mass" option
qinvmass = Canvas(OptionsLep, width=16, height=16)
qinvmass.create_image(8, 8, image=questionmark)

infoinvmass = Message(OptionsLep,
                      text="The invariant mass of the charged leptons",
                      bg="White",
                      aspect=300)  #Information message


def on_enterinvmass(event):
    """shows an explanation if cursor placed over question mark"""
    infoinvmass.grid(row=0, rowspan=8)


def on_leaveinvmass(event):
    """hides explanation if cursor not placed on question mark"""
    infoinvmass.grid_forget()


#Def and bind two functions for when cursor is over question mark or leaves
qinvmass.bind("<Enter>", on_enterinvmass)