Beispiel #1
0
    def initUI(self):
        self.parent.title("WORLD")

        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)  #pack = a geometry manager

        #button
        b = Button(self, text=" GO ", command=self.callback)
        b.pack(side=TOP, padx=15, pady=20)

        #text
        t = Text(self, height=3, width=40)
        t.pack(side=TOP, padx=15)
        t.insert(
            END,
            "Welcome.\nPlease select the number of years\nyou would like to run the Simulation.\n"
        )

        #slider
        slider = Scale(self, from_=0, to=400,
                       command=self.onScale)  #values of slider!
        slider.pack(side=TOP, padx=15)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack(side=TOP, padx=15)
Beispiel #2
0
    def initUI(self):
        self.parent.title("Scale")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)

        scale = Scale(self, from_=0, to=100, command=self.onScale)
        scale.pack(side=LEFT, padx=15)

        self.var = IntVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack(side=LEFT)
    def __init__(self, master, get_gain, set_gain, label=''):
        Frame.__init__(self, master, width=FADER_WIDTH, height=FADER_HEIGHT)
        self.get_gain = get_gain
        self._set_gain = set_gain

        if isinstance(label, StringVar):
            Label(self, textvar=label, width=15).pack()
        else:
            Label(self, text=label, width=15).pack()
        self.gain_label = Label(self)

        gain_scale = Scale(self, from_=1, to=0, command=self.set_gain, orient='vertical')
        gain_scale.set(self.get_gain())
        gain_scale.pack()

        self.gain_label.pack()
    def __init__(self, master, sequencer):
        Frame.__init__(self, master)
        self.sequencer = sequencer

        self.control_label = Label(self, text="Control")

        self.start_button = Button(self, text="Start")
        self.stop_button = Button(self, text="Stop")

        self.start_button.config(command=self.sequencer.play)
        self.stop_button.config(command=self.sequencer.stop)

        self.control_label.pack()
        self.start_button.pack()
        self.stop_button.pack()

        Label(self, text='Tempo').pack()
        self.tempo_label = Label(self)
        self.tempo_label.pack()

        def set_tempo(v):
            tempo = float(v)
            self.sequencer.set_speed(tempo)
            self.tempo_label.config(text='%3.0f' % tempo)

        tempo_scale = Scale(self, from_=400, to=5, command=set_tempo, orient='vertical')
        tempo_scale.set(self.sequencer.speed)
        tempo_scale.pack()

        measure_control_frame = Frame(self)
        measure_control_frame.pack()

        self.measure_resolution = StringVar(measure_control_frame)
        self.measure_resolution.set(self.sequencer.measure_resolution)
        self.beats_per_measure = StringVar(measure_control_frame)
        self.beats_per_measure.set(self.sequencer.beats_per_measure)

        Label(measure_control_frame, text='Resolution').grid(row=0, column=0, sticky='E')
        measure_resolution_entry = Entry(measure_control_frame, textvariable=self.measure_resolution, width=3)
        measure_resolution_entry.grid(row=0, column=1)

        Label(measure_control_frame, text='Beats').grid(row=1, column=0, sticky='E')
        beats_per_measure_entry = Entry(measure_control_frame, textvariable=self.beats_per_measure, width=3)
        beats_per_measure_entry.grid(row=1, column=1)

        change_measure_update = Button(measure_control_frame, text='Update Measure', command=self.change_measures)
        change_measure_update.grid(row=2, columnspan=2)
class mSim(Frame):
  
    def __init__(self, parent):
        
        self.serialStatus = False

        #create variables
        self.startmotor = BooleanVar()
        self.logstate = BooleanVar()
        self.loggedData = []
        self.throttlevar = StringVar()
        self.throttleval = IntVar()

        #default values
        self.throttlevar.set("0%")
        self.throttleval.set(0)

        #base frame init
        Frame.__init__(self, parent)   
        self.parent = parent
        self.initUI()
        self.centerWindow()

        self.PERIOD_LENGTH_Log = 100 #milliseconds
        self.PERIOD_LENGTH_Scan = 1000 #milliseconds
        self.PERIOD_LENGTH_Refresh = 300 #milliseconds

        self.parent.after(0, self.runScan)
        self.parent.after(0, self.runLog)
        self.parent.after(0, self.runRefresh)

    def runScan(self):
        #serial port scanning function
        """ Lists serial port names

            :raises EnvironmentError:
                On unsupported or unknown platforms
            :returns:
                A list of the serial ports available on the system
        """
        if sys.platform.startswith('win'):
            ports = ['COM%s' % (i + 1) for i in range(256)]
        elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
            # this excludes your current terminal "/dev/tty"
            ports = glob.glob('/dev/tty[A-Za-z]*')
        elif sys.platform.startswith('darwin'):
            ports = glob.glob('/dev/tty.*')
        else:
            raise EnvironmentError('Unsupported platform')

        result = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                result.append(port)
            except (OSError, serial.SerialException):
                pass
        menu = self.drop["menu"]
        menu.delete(0, "end")
        menu.add_command(label="None", command=lambda value="None": self.selected_s_Port.set(value))
        for string in result:
            menu.add_command(label=string, command=lambda value=string: self.selected_s_Port.set(value))
                
        self.parent.after(self.PERIOD_LENGTH_Scan, self.runScan)

    def runLog(self):
        #this will probably not work since you're not appending to 
        if (self.logstate.get() == True) and (self.serialStatus == True): #logging data                                        
                    data = dict(zip(*[self.SC.dict.keys(), zip(*self.SC.dict.values())[-1]])) 
                    if 'l' not in locals():         # a dictionary with a deque of the recent data for each message type -Austin
                        l = []
                    if self.loggedData == []: #if empty add titles
                        l=[data.keys()]
                    data = data.values()
                    
                    self.loggedData.append(data)
                    
        self.parent.after(self.PERIOD_LENGTH_Log, self.runLog)

    def runRefresh(self):
        
        #Refresh figures function
        self.a.clear()
        self.b.clear()
        self.c.clear()
        self.d.clear()
        
        if not self.serialStatus:
            #TODO: Put SerialComm data buffer here v . Timestamps (from python?) on x axis, values on y-axis
            #Helpful Info: plot([xvals],[yvals])
            self.a.plot([0],[0])
            self.b.plot([0],[0])
            self.c.plot([0],[0])
            self.d.plot([0],[0])
        else:
            self.SC.processData(5) # This param is the number of bytes to try for a message -Austin
            timestamps = [val / 1000.0  if val != None else val for val in self.SC.dict['Timestamp']]
            self.a.plot(timestamps, self.SC.dict['Thrust'])
            self.b.plot(timestamps, self.SC.dict['Rot Speed'])
            self.c.plot(timestamps, self.SC.dict['Current'])
            self.d.plot(timestamps, self.SC.dict['Voltage'])

        #set labels for graphs (could make automatic later)
        self.a.set_xlabel('time (s)')
        self.a.set_ylabel('Thrust (N)')
        self.b.set_xlabel('time (s)')
        self.b.set_ylabel('RPM')
        self.c.set_xlabel('time (s)')
        self.c.set_ylabel('Current (A)')
        self.d.set_xlabel('time (s)')
        self.d.set_ylabel('Voltage (V)')

        #try drawing the canvas
        try:
            self.canvas.draw()
        except:
            pass #just ignore it, you'll do better next time
        
        self.parent.after(self.PERIOD_LENGTH_Refresh, self.runRefresh)

    def centerWindow(self):
      
        w = 900 #eh, who needs scaling anyways
        h = 600

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        
        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
        

    def initUI(self):

        #Parent Frame
        self.parent.title("Test Stand Control Panel")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)


        # Frame 1 (top)
        frame1 = Frame(self)
        frame1.pack(fill=X, expand=1)

            #Start motor button
        startButton = Button(frame1, text="Start Motor",
            command=self.startMotor)
        startButton.pack(side=LEFT, padx=5, pady=5)     


            #Throttle slider
        lbl1 = Label(frame1, text="Throttle (0-100):", width=14)
        lbl1.pack(side=LEFT, padx=5, pady=5)
        
        self.scale = Scale(frame1, from_=0, to=100, 
            command=self.onScaleThrottle)
        self.scale.pack(side=LEFT, padx=15)
        
        self.label = Label(frame1, text="throttle", textvariable=self.throttlevar, width=5)        
        self.label.pack(side=LEFT)

            #Throttlesweep checkbutton
        self.autovar = BooleanVar()
        cb = Checkbutton(frame1, text="Throttle Sweep",
            variable=self.autovar, command=self.onClickAuto)
        cb.pack(side=LEFT, padx=15)

            #Com port selection field
        droplbl = Label(frame1, text="Serial Port:", width=10)
        droplbl.pack(side=LEFT, padx=5, pady=5)
        self.selected_s_Port = StringVar()
        self.s_Ports = []
        self.drop = OptionMenu(frame1,self.selected_s_Port,"None",*self.s_Ports)
        self.drop.pack(side=LEFT, padx=5)

            #baudrate selection field (disabled)
##       drop2lbl = Label(frame1, text="Baudrate:", width=9)
##        drop2lbl.pack(side=LEFT, padx=5, pady=5)
##        self.baudrate = StringVar()
##        baudrates = [9600, 19200, 38400, 57600, 115200]
##        drop2 = OptionMenu(frame1,self.baudrate,*baudrates)
##        drop2.pack(side=LEFT, padx=5)

            #Start serial button
        comsButton = Button(frame1, text="Start Serial",
            command=self.startSerial)
        comsButton.pack(side=LEFT, padx=5, pady=5)

            #Stop serial button
        comsStopButton = Button(frame1, text="Stop Serial",
            command=self.stopSerial)
        comsStopButton.pack(side=LEFT, padx=5, pady=5)

        # Frame 2 (second line)
        frame2 = Frame(self)
        frame2.pack(fill=X, expand=1)

            #Amperage entry
        lbl2 = Label(frame2, text="Max Motor Current (A):", width=21)
        lbl2.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxA_Entry = Entry(frame2)
        self.MaxA_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxA_Entry.insert(0, 10)

            #Voltage entry
        lbl3 = Label(frame2, text="Max Motor Voltage (V):", width=20)
        lbl3.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxV_Entry = Entry(frame2)
        self.MaxV_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxV_Entry.insert(0, 14)

            #Update button
        updateButton = Button(frame2, text="Update Values",
            command=self.updateValues)
        updateButton.pack(side=LEFT, padx=5, pady=5)
        
        # Graph Frame
        framegraph = Frame(self)
        framegraph.pack(fill=X, expand=1)

            #Init figures
        f = Figure(figsize=(4,4), dpi=100)
        self.a = f.add_subplot(2, 2, 1)
        self.d = f.add_subplot(2, 2, 4)
        self.c = f.add_subplot(2, 2, 3)
        self.b = f.add_subplot(2, 2, 2)
        
        f.set_tight_layout(True)

        self.canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

            #Display Toolbar
        toolbar = NavigationToolbar2TkAgg(self.canvas, framegraph)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        
        # Frame 0 (Bottom text)
        frame0 = Frame(self)
        frame0.pack(side="bottom", fill="x", expand=1)

            #Display text (allows to give user information)
        self.textboxvar = StringVar()
        self.info = Label(frame0, textvariable=self.textboxvar)
        self.info.pack(side=LEFT, padx=5, pady=5)

        # Button Frame (large buttons, near bottom)
        s = Style() #has its own style
        s.configure('My.TFrame',background='#f7edc3') #fancy colors
        framered = Frame(self, style='My.TFrame')
        framered.pack(side="bottom", fill="x", expand=1)
        #used the tk instead of ttk library for this, allows font and color mods

            #Save Button
        self.saveButton = tk.Button(framered, text="Save Data", bg='green', font=('Arial',20,'bold'),
            command=self.saveData)
        self.saveButton.pack(side="left", padx=5, pady=5)

            #Log button
        self.logButton = tk.Button(framered, text="Start Data Logging", bg="blue", font=('Arial',20,'bold'),
            command=self.logData)
        self.logButton.pack(side="left", padx=5, pady=5)

            #Stop button
        self.stopButton = tk.Button(framered, text="Stop Motor", bg='red', font=('Arial',20,'bold'),
            command=self.stopMotor)
        self.stopButton.pack(side="right", padx=5, pady=5)
         

    #Button behavior functions (hopefully self-explanatory)
         
    def onClickAuto(self): #for the throttle sweep (should rename)
        pass #(I guess I can make it do something if I want)

    def MaxA(self):
        #self.MaxA_Entry.get()
        pass
            
    def MaxV(self):
        pass #not sure why these are even functions

    def onScaleThrottle(self, val):
        throttle = str(int(float(val)))
        self.throttlevar.set(throttle + "%")
        self.throttleval.set(throttle)
        try:
            self.SC.sendThrottleSetting(self.throttleval.get())
        except:
            self.textboxvar.set("Something went wrong, is serial connected?")

    def startSerial(self):
        COM_Port = self.selected_s_Port.get()
        #print type(COM_Port)
        #print COM_Port
        if "COM" in COM_Port:
            self.textboxvar.set("Starting Serial on port " + self.selected_s_Port.get())
            #serialThread = Thread(target=SerialComm, args=(COM_Port)) #probably want to pass the self.vars?
            #serialThread.start()
            #threads.append(serialThread)
            try:
                self.ser = serial.Serial(self.selected_s_Port.get(), 9600) #Baud rate = 9600
                self.SC = SerialComm(self.ser, 50) #Dict deques' maxlength = 50
                
                for key in self.SC.dict.keys(): #Initialize dict deques with values so no length errors -Austin
                    for i in range(self.SC.dict[key].maxlen):
                        self.SC.dict[key].append(None)
                
                self.serialStatus = True
            except Exception,e: #if the com port is wrong dont start serial
                print str(e)
                self.textboxvar.set("Error starting serial on port " + self.selected_s_Port.get() + ": " + str(e))
        else:
Beispiel #6
0
class qual_window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI(parent)

    def initUI(self, parent):
        # initalising some variables
        self.Quality_e = None
        self.scale = None
        self.fmemory_e = None
        self.memory_e = None

        self.style = Style()
        self.style.theme_use("classic")
        Style().configure("TEntry", font='serif 10')
        Style().configure("TLabel", font='serif 10')

        # creating menubar
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Restart", command=self.re_start)
        menubar.add_cascade(label="Options", menu=fileMenu)

        # creating layout from frames
        self.frame3 = Frame(parent, relief="sunken")
        self.frame3.pack(side="bottom", fill=X)
        self.frame1 = Frame(parent, relief="sunken")
        self.frame1.pack(side="left", fill=Y)
        self.frame2 = Frame(parent,
                            width=gbl.x2 - gbl.x1,
                            height=max(gbl.y2 - gbl.y1, 200),
                            relief="flat",
                            bg="#333")
        self.frame2.pack(side="right", fill="both", expand="True")

        # creating canvas in frame 2
        self.canvas = Canvas(self.frame2)
        self.canvas.pack(fill="both", expand="True")

        # creating save and next Button
        self.b9 = Button(self.frame1,
                         text="Save and Next>>",
                         state="active",
                         font='serif 10',
                         command=self.save_next)
        self.b9.pack(side="bottom", pady=5)
        self.b9.bind('<Return>', self.save_next)
        self.b8 = Button(self.frame1,
                         text="<<Back",
                         state="active",
                         font='serif 10',
                         command=self.go_back)
        self.b8.pack(side="bottom", pady=5)
        self.b8.bind('<Return>', self.go_back)
        self.parent.bind('<Return>', self.save_next)

        # track for editable entries
        self.e1s = StringVar(self.frame1)
        self.e2s = StringVar(self.frame1)
        self.e1s.trace("w", self.check)
        self.e2s.trace("w", self.check)

        # creating editable format and quality entries
        # self.format_e = self.make_entry(gbl.out_format, "Format (Default JPEG)")
        self.format_e = Entry(self.frame1,
                              textvariable=self.e1s,
                              bg="white",
                              bd=4,
                              cursor="xterm",
                              fg="Black",
                              justify="center",
                              relief="ridge")
        self.format_e.insert(0, "JPEG")
        self.format_e.pack(side="top")
        Label(self.frame1, text="Format (Default JPEG)").pack(side="top")

        # self.Quality_e = self.make_entry(gbl.Quality, "Format (Default 80)")
        self.Quality_e = Entry(self.frame1,
                               textvariable=self.e2s,
                               bg="white",
                               bd=4,
                               cursor="xterm",
                               fg="Black",
                               justify="center",
                               relief="ridge")
        self.Quality_e.insert(0, gbl.Quality)
        self.Quality_e.pack(side="top")
        Label(self.frame1, text="Quality (Default 80)").pack(side="top")
        # self.format_e.config(textvariable=self.e1s)
        # self.Quality_e.config(textvariable=self.e2s)

        # creating sliding bar
        self.var = IntVar()
        self.scale = Scale(self.frame1,
                           from_=1,
                           to=100,
                           orient="horizontal",
                           length=168,
                           command=self.onScale)
        self.scale.set(gbl.Quality)
        self.scale.pack(side="top")

        self.l1 = Label(self.frame1, textvariable=self.var)
        self.l1.pack(side="top")
        self.var.set(gbl.Quality)

        # saving and putting PIL.Image in canvas
        self.save_put_image()

        # creating memory entries
        self.fmemory_e = self.set_memory_entry(self.frame1, "Final",
                                               gbl.output_file)
        self.memory_e = self.set_memory_entry(self.frame1, "Initial",
                                              gbl.input_file)

        # creating status bar
        Label(self.frame3, text=gbl.output_file).pack(side="left", anchor="w")
        Label(self.frame3, text=str(gbl.cu_ind) + "/" +
              str(gbl.total_files)).pack(side="right", anchor="e")

    # def make_entry(self, data, text_):
    # 	temp_entry = Entry(self.frame1, textvariable=None, bg="white", bd=4, cursor="xterm", fg="Black", justify="center", relief="ridge")
    # 	temp_entry.insert(0,data)
    # 	temp_entry.pack(side="top")
    # 	Label(self.frame1, text=text_).pack(side="top")
    # 	return temp_entry

    def quality_entered(self):
        gbl.out_format = str(self.format_e.get())
        gbl.Quality = int(self.Quality_e.get())
        if (self.scale != None):
            self.scale.set(gbl.Quality)
            self.var.set(gbl.Quality)
            self.save_put_image()

    def onScale(self, val):
        v = int(float(val))
        self.var.set(v)
        self.Quality_e.delete(0, 'end')
        self.Quality_e.insert(0, v)

    def check(self, *args):
        if (self.Quality_e != None):
            e1_data = self.e1s.get()
            e2_data = self.e2s.get()
            if (e1_data in ["JPEG", "PNG"]) and e2_data.isdigit(
            ) and int(e2_data) <= 100 and int(e2_data) > 0:
                self.b9.config(state="active")
                self.b9.bind('<Return>', self.save_next)
                self.quality_entered()
            else:
                self.b9.config(state="disabled")
                self.b9.unbind('<Return>')

    def save_next(self, *args):
        if (os.path.isfile(gbl.output_file + "temp")):
            os.remove(gbl.output_file + "temp")
        self.quit()

    def go_back(self, *args):
        if (os.path.isfile(gbl.output_file + "temp")):
            os.remove(gbl.output_file + "temp")
        gbl.back = 1
        gbl.cu_ind -= 1
        self.quit()

    def save_put_image(self):
        if (os.path.isfile(gbl.output_file)):
            os.remove(gbl.output_file)
        if (os.path.isfile(gbl.output_file + "temp")):
            os.remove(gbl.output_file + "temp")
        gbl.crop_im.save(gbl.output_file + "temp",
                         gbl.out_format,
                         quality=gbl.Quality,
                         progressive=True,
                         optimize=True)
        gbl.main_crop_im.save(gbl.output_file,
                              gbl.out_format,
                              quality=gbl.Quality,
                              progressive=True,
                              optimize=True)
        self.temp_im = PIL.Image.open(gbl.output_file + "temp")
        self.fc_im = PIL.ImageTk.PhotoImage(self.temp_im)
        gbl.crop_im_canv = self.canvas.create_image(
            (gbl.x2 - gbl.x1) / 2,
            max(gbl.y2 - gbl.y1, 600) / 2,
            image=self.fc_im)
        if (self.fmemory_e != None):
            self.memory = (os.path.getsize(gbl.output_file) * 1.0) / 1024
            self.fmemory_e.config(state="normal")
            self.fmemory_e.delete(0, 'end')
            self.fmemory_e.insert(0, self.memory)
            self.fmemory_e.config(state="readonly")

    def set_memory_entry(self, framei, text_, file_name):
        temp_entry = Entry(framei,
                           bg="white",
                           bd=4,
                           cursor="xterm",
                           fg="Black",
                           justify="center",
                           relief="ridge")
        memory = (os.path.getsize(file_name) * 1.0) / 1024
        temp_entry.insert(0, memory)
        temp_entry.config(state="readonly")
        temp_entry.pack(side="top")
        Label(framei, text=text_ + " Memory (KB)").pack(side="top")
        return temp_entry

    def crop_size(self):
        if ((gbl.w * 1.0) / gbl.h >= (int(gbl.width) * 1.0) / int(gbl.height)):
            cropx = ((gbl.height * gbl.w) -
                     (gbl.width * gbl.h)) / (gbl.height * 2)
            cropy = 0
        else:
            cropx = 0
            cropy = ((gbl.width * gbl.h) -
                     (gbl.height * gbl.w)) / (gbl.width * 2)
        return cropx, cropy

    def re_start(self):
        gbl.go_restart = 1
        self.quit()
    def initUI(self):

        #Parent Frame
        self.parent.title("Test Stand Control Panel")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)


        # Frame 1 (top)
        frame1 = Frame(self)
        frame1.pack(fill=X, expand=1)

            #Start motor button
        startButton = Button(frame1, text="Start Motor",
            command=self.startMotor)
        startButton.pack(side=LEFT, padx=5, pady=5)     


            #Throttle slider
        lbl1 = Label(frame1, text="Throttle (0-100):", width=14)
        lbl1.pack(side=LEFT, padx=5, pady=5)
        
        scale = Scale(frame1, from_=0, to=100, 
            command=self.onScaleThrottle)
        scale.pack(side=LEFT, padx=15)
        
        self.throttlevar = StringVar()
        self.throttleval = IntVar()
        self.label = Label(frame1, text="throttle", textvariable=self.throttlevar, width=5)        
        self.label.pack(side=LEFT)

            #Throttlesweep checkbutton
        self.autovar = BooleanVar()
        cb = Checkbutton(frame1, text="Throttle Sweep",
            variable=self.autovar, command=self.onClickAuto)
        cb.pack(side=LEFT, padx=15)

            #Com port selection field
        droplbl = Label(frame1, text="Serial Port:", width=10)
        droplbl.pack(side=LEFT, padx=5, pady=5)
        self.selected_s_Port = StringVar()
        self.s_Ports = []
        drop = OptionMenu(frame1,self.selected_s_Port,"None",*self.s_Ports)
        drop.pack(side=LEFT, padx=5)

            #baudrate selection field (disabled)
##        drop2lbl = Label(frame1, text="Baudrate:", width=9)
##        drop2lbl.pack(side=LEFT, padx=5, pady=5)
##        self.baudrate = StringVar()
##        baudrates = [9600, 19200, 38400, 57600, 115200]
##        drop2 = OptionMenu(frame1,self.baudrate,*baudrates)
##        drop2.pack(side=LEFT, padx=5)

            #Start serial button
        comsButton = Button(frame1, text="Start Serial",
            command=self.startSerial)
        comsButton.pack(side=LEFT, padx=5, pady=5)

            #Stop serial button
        comsStopButton = Button(frame1, text="Stop Serial",
            command=self.stopSerial)
        comsStopButton.pack(side=LEFT, padx=5, pady=5)

        # Frame 2 (second line)
        frame2 = Frame(self)
        frame2.pack(fill=X, expand=1)

            #Amperage entry
        lbl2 = Label(frame2, text="Max Motor Current (A):", width=21)
        lbl2.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxA_Entry = Entry(frame2)
        self.MaxA_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxA_Entry.insert(0, 10)

            #Voltage entry
        lbl3 = Label(frame2, text="Max Motor Voltage (V):", width=20)
        lbl3.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxV_Entry = Entry(frame2)
        self.MaxV_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxV_Entry.insert(0, 14)

            #Update button
        updateButton = Button(frame2, text="Update Values",
            command=self.updateValues)
        updateButton.pack(side=LEFT, padx=5, pady=5)
        
        # Graph Frame
        framegraph = Frame(self)
        framegraph.pack(fill=X, expand=1)

            #Init figures
        f = Figure(figsize=(4.5,4.5), dpi=100)
        self.a = f.add_subplot(2, 2, 1)
        self.d = f.add_subplot(2, 2, 4)
        self.c = f.add_subplot(2, 2, 3)
        self.b = f.add_subplot(2, 2, 2)
        
        f.set_tight_layout(True)

        self.canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

            #Display Toolbar
        toolbar = NavigationToolbar2TkAgg(self.canvas, framegraph)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

            #Refresh thread function
        def refreshFigure(): #this is threaded and just refreshes the figure (see time.sleep() for refresh rate)
            time.sleep(1)
            while True  and (not exitapp):
                self.a.clear()
                self.b.clear()
                self.c.clear()
                self.d.clear()
                if not serialStatus:
                    self.a.plot([1,2,3,4,5,6,7,8],[0,0,0,0,0,0,0,0])
                    self.b.plot([1,2,3,4,5,6,7,8],[0,0,0,0,0,0,0,0])
                    self.c.plot([1,2,3,4,5,6,7,8],[0,0,0,0,0,0,0,0])
                    self.d.plot([1,2,3,4,5,6,7,8],[0,0,0,0,0,0,0,0])
                else:
                    #debug plotsTimestamp
                    self.a.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Timestamp"])
                    self.b.plot(serialData[-10:]["Timestamp"],serialData[-10:]["raw_temp"])
                    self.c.plot(serialData[-10:]["Timestamp"],serialData[-10:]["conv_temp"])
                    self.d.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Potentiometer"])
                    #final plots
    ##                self.a.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Thrust"])
    ##                self.b.plot(serialData[-10:]["Timestamp"],serialData[-10:]["RPM"])
    ##                self.c.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Current"])
    ##                self.d.plot(serialData[-10:]["Timestamp"],serialData[-10:]["Voltage"])
                    #old demo stuff
    ##                self.a.plot([1,2,3,4,5,6,7,8],[5,6,1,3,self.throttleval.get(),9,3,5])
    ##                self.b.plot([1,2,3,4,5,6,7,8],[3,16,10,30,80,90,30,50])
    ##                self.c.plot([1,2,3,4,5,6,7,8],[8,5,4,(self.throttleval.get())**(0.5),15,15,15,20])
    ##                self.d.plot([1,2,3,4,5,6,7,8],[14,14,13,12,12,11.5,11.2,10.5])

                #set labels for graphs (could make automatic later)
                self.a.set_xlabel('time (s)')
                self.a.set_ylabel('Thrust (N)')
                self.b.set_xlabel('time (s)')
                self.b.set_ylabel('RPM')
                self.c.set_xlabel('time (s)')
                self.c.set_ylabel('Current (A)')
                self.d.set_xlabel('time (s)')
                self.d.set_ylabel('Voltage (V)')

                #try drawing the canvas
                try:
                    self.canvas.draw()
                except:
                    pass #just ignore it, you'll do better next time
                time.sleep(0.1) #refreshrate
        ###END FUNCTION###

            #Start the graphing thread
        plotThread = Thread(target=refreshFigure, args=())
        plotThread.start()
        threads.append(plotThread)
        
        # Frame 0 (Bottom text)
        frame0 = Frame(self)
        frame0.pack(side="bottom", fill="x", expand=1)

            #Display text (allows to give user information)
        self.textboxvar = StringVar()
        self.info = Label(frame0, textvariable=self.textboxvar)
        self.info.pack(side=LEFT, padx=5, pady=5)

        # Button Frame (large buttons, near bottom)
        s = Style() #has its own style
        s.configure('My.TFrame',background='#f7edc3') #fancy colors
        framered = Frame(self, style='My.TFrame')
        framered.pack(side="bottom", fill="x", expand=1)
        #used the tk instead of ttk library for this, allows font and color mods

            #Save Button
        self.saveButton = tk.Button(framered, text="Save Data", bg='green', font=('Arial',20,'bold'),
            command=self.saveData)
        self.saveButton.pack(side="left", padx=5, pady=5)

            #Log button
        self.logButton = tk.Button(framered, text="Start Data Logging", bg="blue", font=('Arial',20,'bold'),
            command=self.logData)
        self.logButton.pack(side="left", padx=5, pady=5)

            #Stop button
        self.stopButton = tk.Button(framered, text="Stop Motor", bg='red', font=('Arial',20,'bold'),
            command=self.stopMotor)
        self.stopButton.pack(side="right", padx=5, pady=5)
Beispiel #8
0
sc_var = StringVar()
lbsc_var = IntVar()

icon = PhotoImage(name="icon", file=dico_scales.get(1)[2])

lb_display = Label(root, compound="right", image=icon)

sc_test = Scale(root, orient=HORIZONTAL, variable=sc_var, from_=1, to=7, command=_scale_update)


#### former codelines from ProfileForm.py (line 389 +)
##self.lb_icon_minscale = Label(self.FrDivers, image = self.icon_inspire)
##self.sc_geoscale = Scale(self.FrDivers, orient=HORIZONTAL, label = "échelle",
##                         from_= 5000, to = 150000, tickinterval = 10000, troughcolor="cyan",
##                         resolution = 50000, sliderlength=50)
##self.lb_icon_maxscale = Label(self.FrDivers, image = self.icon_new_profile)
##
##self.lb_icon_minscale.grid(row = 4, column = 0, pady = 3, sticky = "w")
##self.lb_icon_maxscale.grid(row = 4, column = 3, pady = 3, sticky = "e")
##self.sc_geoscale.grid(row = 4, column = 0, columnspan = 4, padx = 55, pady = 3, sticky = "we")


sc_test.pack()
lb_display.pack()


lbsc_test = LabeledScale(root, variable=lbsc_var)
lbsc_test.pack()

root.mainloop(0)