コード例 #1
0
    def initUI(self):

        self.parent.title("Listbox + Scale + ChkBtn")
        self.pack(fill=BOTH, expand=1)
        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.place(x=20, y=190)

        scale = Scale(self, from_=0, to=100, command=self.onScale)
        scale.place(x=20, y=220)

        self.var_scale = IntVar()
        self.label_scale = Label(self, text=0, textvariable=self.var_scale)
        self.label_scale.place(x=180, y=220)

        self.var_chk = IntVar()
        cb = Checkbutton(self, text="Test", variable=self.var_chk,
                command=self.onClick)
        cb.select()
        cb.place(x=220, y=60)
コード例 #2
0
 def MakeCB(self, cb_ptr, text, evt_type, arg, csp=1, stky=W):
     cb_ptr = Checkbutton(self, text=text)
     cb_ptr.bind(evt_type, lambda event, arg=arg: self.toggle_cb(event, arg))
     if self.orig[arg]:
         cb_ptr.select()
     cb_ptr.grid(row=self.row, column=self.col, columnspan=csp, sticky=W)
     self.row += 1
コード例 #3
0
    def create_other_buttons(self):
        f = self.make_frame()[0]

        btn = Checkbutton(f, anchor="w",
                variable=self.recvar,
                text="Recurse down subdirectories")
        btn.pack(side="top", fill="both")
        btn.select()
コード例 #4
0
ファイル: GrepDialog.py プロジェクト: Darriall/pypy
    def create_other_buttons(self):
        f = self.make_frame()[0]

        btn = Checkbutton(f, anchor="w",
                variable=self.recvar,
                text="Recurse down subdirectories")
        btn.pack(side="top", fill="both")
        btn.select()
コード例 #5
0
ファイル: check_box.py プロジェクト: alistairwalsh/samebright
    def initUI(self):
      
        self.parent.title("Checkbutton")

        self.pack(fill=BOTH, expand=1)
        self.var = IntVar()
        
        cb = Checkbutton(self, text="Show title",
            variable=self.var, command=self.onClick)
        cb.select()
        cb.place(x=50, y=50)
コード例 #6
0
ファイル: checkbutton.py プロジェクト: nfredrik/tkinter
    def initUI(self):
      
        self.parent.title("Checkbutton")

        self.pack(fill=BOTH, expand=1)
        self.var = IntVar()
        
        cb = Checkbutton(self, text="Show title",
            variable=self.var, command=self.onClick)
        cb.select()
        cb.place(x=50, y=50)
コード例 #7
0
ファイル: tmp.py プロジェクト: myanime/amazon_script
    def initUI(self):
      
        self.parent.title("Checkbutton")

        self.pack(fill=BOTH, expand=True)
        self.var = BooleanVar()
        submit = Submitbutton(self)
        cb = Checkbutton(self, text="Show title",
            variable=self.var, command=self.onClick)
        cb.select()
        cb.place(x=50, y=50)
        submit.place(x=5, y=5)
コード例 #8
0
ファイル: SearchDialogBase.py プロジェクト: 0xcc/python-read
    def create_option_buttons(self):
        "Fill frame with Checkbuttons bound to SearchEngine booleanvars."
        f = self.make_frame("Options")

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.revar,
                text="Regular expression")
        btn.pack(side="left", fill="both")
        if self.engine.isre():
            btn.select()

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.casevar,
                text="Match case")
        btn.pack(side="left", fill="both")
        if self.engine.iscase():
            btn.select()

        btn = Checkbutton(f, anchor="w",
                variable=self.engine.wordvar,
                text="Whole word")
        btn.pack(side="left", fill="both")
        if self.engine.isword():
            btn.select()

        if self.needwrapbutton:
            btn = Checkbutton(f, anchor="w",
                    variable=self.engine.wrapvar,
                    text="Wrap around")
            btn.pack(side="left", fill="both")
            if self.engine.iswrap():
                btn.select()
コード例 #9
0
class TimeBase(Frame):
    """
    Base de temps

    scale_time : controle  de la base de temps
    """
    def __init__(self, parent=None):
        """
        Initialisation

        parent : oscilloscope
        """
        Frame.__init__(self)
        self.configure(bd=1, relief="sunken")
        self.parent = parent
        self.scale_time = Scale(self,
                                length=100,
                                orient="horizontal",
                                label="Temps",
                                showvalue=1,
                                from_=1,
                                to=10,
                                tickinterval=1,
                                command=self.update)
        self.scale_time.pack(expand="yes", fill="both")

        # choix d'afficher lissajoux ou pas
        self.check = Checkbutton(self,
                                 text="Afficher lissajou",
                                 selectcolor=self.parent.lissajoux.color_XY,
                                 command=self.parent.plot_all,
                                 variable=self.parent.drawXY,
                                 onvalue=1,
                                 offvalue=0)
        self.check.pack(side="top", expand="yes", fill="x")
        self.check.select()

    def get_time(self):
        """
        recuperer la valeur courante de la base de temps
        """
        return self.scale_time.get()

    def update(self, event):
        """mise a jour de la base de temps"""
        print("TimeBase.update_time_base()")
        print("Base de temps : ", self.scale_time.get())
        if not isinstance(self.parent, Tk):
            self.parent.update_time(self.scale_time.get())
コード例 #10
0
ファイル: gui.py プロジェクト: Bromind/yaomr
class MainGui:
    def __init__(self, master):
        self.master = master
        master.title("YAOMC")
        self.file_button = Button(master,
                                  text="Select scores",
                                  command=self.pick_file)
        self.folder_button = Button(master,
                                    text="Select Output folder",
                                    command=self.pick_folder)
        self.gen_button = Button(master,
                                 text="Generate",
                                 command=lines.separate_lines)
        self.exit_button = Button(master, text="Exit", command=master.quit)
        self.folder_text = StringVar()
        self.file_text = StringVar()
        self.folder_text.set("none." if outputfolder == '' else outputfolder)
        self.file_text.set("none." if inputfile == '' else inputfile)
        param.outdir = "none." if outputfolder == '' else outputfolder
        param.infile = "none." if inputfile == '' else inputfile
        self.folder_label = Label(master, textvariable=self.folder_text)
        self.file_label = Label(master, textvariable=self.file_text)
        self.build_check = Checkbutton(master, text="build")
        self.midi_check = Checkbutton(master, text="midi")
        self.build_check.select()
        self.midi_check.select()
        self.file_label.grid(row=1, column=2, sticky=W)
        self.folder_label.grid(row=2, column=2, sticky=W)
        self.file_button.grid(row=1, column=1, sticky=W)
        self.folder_button.grid(row=2, column=1, sticky=W)
        self.gen_button.grid(row=3, column=1)
        self.exit_button.grid(row=3, column=2)
        self.build_check.grid(row=4, column=1)
        self.midi_check.grid(row=4, column=2)

    def pick_file(self):
        param.infile = tkFileDialog.askopenfilename(
            initialdir=".",
            title="Select scores",
            filetypes=(("png files", "*.png"), ("all files", "*.*")))
        self.file_text.set(param.infile)

    def pick_folder(self):
        param.outdir = tkFileDialog.askdirectory(initialdir=".")
        self.folder_text.set(param.outdir)
コード例 #11
0
    def initUI(self):
      
        self.parent.title("Checkbutton")

        self.pack(fill=BOTH, expand=1)
        self.var = IntVar()
        #We create an IntVar object. 
        #It is a value holder for integer values for widgets in Tkinter.
        
        cb = Checkbutton(self, text="Show title",
            variable=self.var, command=self.onClick)
        #An instance of the Checkbutton is created. 
        #The value holder is connected to the widget via the variable parameter. 
        #When we click on the check button, the onClick() method is called. 
        #This is done with the command parameter.
        cb.select()
        #Initially, the title is shown in the titlebar. 
        #So at the start, we make it checked with the select() method.
        cb.place(x=50, y=50)
コード例 #12
0
    def create_option_buttons(self):
        '''Return (filled frame, options) for testing.

        Options is a list of SearchEngine booleanvar, label pairs.
        A gridded frame from make_frame is filled with a Checkbutton
        for each pair, bound to the var, with the corresponding label.
        '''
        frame = self.make_frame("Options")[0]
        engine = self.engine
        options = [(engine.revar, "Regular expression"),
                   (engine.casevar, "Match case"),
                   (engine.wordvar, "Whole word")]
        if self.needwrapbutton:
            options.append((engine.wrapvar, "Wrap around"))
        for var, label in options:
            btn = Checkbutton(frame, anchor="w", variable=var, text=label)
            btn.pack(side="left", fill="both")
            if var.get():
                btn.select()
        return frame, options
コード例 #13
0
    def create_option_buttons(self):
        '''Return (filled frame, options) for testing.

        Options is a list of SearchEngine booleanvar, label pairs.
        A gridded frame from make_frame is filled with a Checkbutton
        for each pair, bound to the var, with the corresponding label.
        '''
        frame = self.make_frame("Options")[0]
        engine = self.engine
        options = [(engine.revar, "Regular expression"),
                   (engine.casevar, "Match case"),
                   (engine.wordvar, "Whole word")]
        if self.needwrapbutton:
            options.append((engine.wrapvar, "Wrap around"))
        for var, label in options:
            btn = Checkbutton(frame, anchor="w", variable=var, text=label)
            btn.pack(side="left", fill="both")
            if var.get():
                btn.select()
        return frame, options
コード例 #14
0
class TimeBase(Frame):
    """
    Base de temps

    scale_time : controle  de la base de temps
    """
    def __init__(self, parent=None):
        """
        Initialisation

        parent : oscilloscope
        """
        Frame.__init__(self)
        self.configure(bd=1, relief="sunken")
        self.parent = parent
        self.scale_time = Scale(self, length=100, orient="horizontal",
                label="Temps", showvalue=1, from_=1, to=10,
                tickinterval=1, command=self.update)
        self.scale_time.pack(expand="yes", fill="both")

        # choix d'afficher lissajoux ou pas
        self.check = Checkbutton(self,text="Afficher lissajou", selectcolor=self.parent.lissajoux.color_XY,  command=self.parent.plot_all, variable=self.parent.drawXY, onvalue = 1, offvalue = 0)
        self.check.pack(side="top",expand="yes", fill="x")
        self.check.select()

    def get_time(self):
        """
        recuperer la valeur courante de la base de temps
        """
        return self.scale_time.get()

    def update(self, event):
        """mise a jour de la base de temps"""
        print("TimeBase.update_time_base()")
        print("Base de temps : ", self.scale_time.get())
        if not isinstance(self.parent, Tk):
            self.parent.update_time(self.scale_time.get())
コード例 #15
0
    def create_option_buttons(self):
        "Fill frame with Checkbuttons bound to SearchEngine booleanvars."
        f = self.make_frame("Options")

        btn = Checkbutton(f,
                          anchor="w",
                          variable=self.engine.revar,
                          text="Regular expression")
        btn.pack(side="left", fill="both")
        if self.engine.isre():
            btn.select()

        btn = Checkbutton(f,
                          anchor="w",
                          variable=self.engine.casevar,
                          text="Match case")
        btn.pack(side="left", fill="both")
        if self.engine.iscase():
            btn.select()

        btn = Checkbutton(f,
                          anchor="w",
                          variable=self.engine.wordvar,
                          text="Whole word")
        btn.pack(side="left", fill="both")
        if self.engine.isword():
            btn.select()

        if self.needwrapbutton:
            btn = Checkbutton(f,
                              anchor="w",
                              variable=self.engine.wrapvar,
                              text="Wrap around")
            btn.pack(side="left", fill="both")
            if self.engine.iswrap():
                btn.select()
コード例 #16
0
ファイル: find_SPE_GUI.py プロジェクト: jjgomezcadenas/IC
	def initUI(self):

		self.parent.title("FIND SPE VALUE")
		self.pack(fill=BOTH, expand=True)

		self.columnconfigure(0, weight=1)
		#self.rowconfigure(0, weight=1)
		# weight attibute is used to make them growable

		self.graph_cb  = BooleanVar()
		self.bins      = IntVar()
		self.path      = StringVar()
		self.n_files   = IntVar()
		self.start_s   = IntVar()
		self.end_s     = IntVar()
		self.guess     = IntVar()


		search = Image.open("next_logo.jpg")
		search_temp = search.resize((160, 200), Image.ANTIALIAS)
		search_aux = ImageTk.PhotoImage(search_temp)
		label1 = Label(self, image=search_aux)
		label1.image = search_aux
		label1.grid(row=0, column=0,
				columnspan=10, rowspan=10, sticky=E+W+S+N)


		#Number of Files and Bins. Spin Box
		self.n_files.set("2000")
		sb1 = Spinbox(self, from_=1, to=10000,
				  width=6, textvariable=self.n_files)
		sb1.grid(row=1,column=4, sticky=W)
		sb1_label = Label(self, text="Files")
		sb1_label.grid(row=1,column=3, padx=5, sticky=E)

		self.bins.set("50")
		sb2 = Spinbox(self, from_=10, to=200,
				  width=6, textvariable=self.bins)
		sb2.grid(row=1,column=6, sticky=W)
		sb2_label = Label(self, text="Hist. Bins")
		sb2_label.grid(row=1,column=5, padx=5, sticky=E)

		# INTEGRATION LIMITS
		Integration_label = Label(self, text="INTEGRATION",
		                          font = "Verdana 12 bold")
		Integration_label.grid(row=3,column=4,
						padx=5,
						columnspan = 2)
		self.start_s.set("1732")
		sb3 = Spinbox(self, from_=1, to=10000,
				  width=6, textvariable=self.start_s)
		sb3.grid(row=4,column=4, sticky=W)
		sb3_label = Label(self, text="StartPoint")
		sb3_label.grid(row=4,column=3, padx=5, sticky=E)

		self.end_s.set("1752")
		sb4 = Spinbox(self, from_=1, to=10000,
				  width=6, textvariable=self.end_s)
		sb4.grid(row=4,column=6, sticky=W)
		sb4_label = Label(self, text="EndPoint")
		sb4_label.grid(row=4,column=5, padx=5, sticky=E)
		sb4_label = Label(self, text="")
		sb4_label.grid(row=4,column=7, padx=5, sticky=E)

		# FITTING PARAMETERS
		Integration_label = Label(self, text="FITTING",
		                          font = "Verdana 12 bold")
		Integration_label.grid(row=6,column=4,
						padx=5,
						columnspan = 2)
		self.guess.set("-20")
		sb5 = Spinbox(self, from_=-50, to=-1,
				  width=6, textvariable=self.guess)
		sb5.grid(row=7,column=4, sticky=W)
		sb5_label = Label(self, text="SPE guess")
		sb5_label.grid(row=7,column=5, padx=5, sticky=W)

		#Check buttons
		cb1 = Checkbutton(self, text="MultiGraph Output", variable=self.graph_cb					)
		cb1.select()
		cb1.grid(row=7,column=6, sticky=W)


		#Text Box
		#self.path.set("F:/DATOS_DAC/spe_1230/2046/pmt_0_trace_evt_")
		self.path.set("spe_1230_2046.h5.z")
		e1 = Entry(self, textvariable=self.path, width=45)
		e1.grid(row=10,column=3, sticky=W, columnspan=10, padx=10, pady=5)
		e1_label = Label(self, text="DataSet path (including name file)")
		e1_label.grid(row=9,column=3,sticky=W, columnspan=10, padx=10)


		# Main buttons
		obtn = Button(self, text="GO!!", command=self.SPE_f)
		obtn.grid(row=14, column=5, sticky=E, pady=5)

		cbtn = Button(self, text="Quit", command=self.quit)
		cbtn.grid(row=14, column=6, sticky=E, pady=5)

		hbtn = Button(self, text="Help")
		hbtn.grid(row=14, column=0, sticky=W, pady=5)
コード例 #17
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()
コード例 #18
0
class Screen(Observer):
    def __init__(self, parent, model_x, model_y, bg="white"):
        self.canvas = Canvas(parent, bg=bg)
        self.model_x = model_x
        self.model_y = model_y
        print("parent", parent.cget("width"), parent.cget("height"))

        self.showX = True
        self.showY = True

        self.frame = Frame(parent)
        # Signal X
        self.magnitude_x = Scale(self.frame,
                                 length=250,
                                 orient="horizontal",
                                 name="m_x",
                                 label="Magnitude X",
                                 sliderlength=20,
                                 showvalue=0,
                                 from_=0,
                                 to=5,
                                 tickinterval=25)
        self.frequency_x = Scale(self.frame,
                                 length=250,
                                 orient="horizontal",
                                 name="f_x",
                                 label="Frequency X",
                                 sliderlength=20,
                                 showvalue=0,
                                 from_=0,
                                 to=5,
                                 tickinterval=25)
        self.phase_x = Scale(self.frame,
                             length=250,
                             orient="horizontal",
                             name="p_x",
                             label="Phase X",
                             sliderlength=20,
                             showvalue=0,
                             from_=0,
                             to=5,
                             tickinterval=25)
        # Signal Y
        self.magnitude_y = Scale(self.frame,
                                 length=250,
                                 orient="horizontal",
                                 name="m_y",
                                 label="Magnitude Y",
                                 sliderlength=20,
                                 showvalue=0,
                                 from_=0,
                                 to=5,
                                 tickinterval=25)
        self.frequency_y = Scale(self.frame,
                                 length=250,
                                 orient="horizontal",
                                 name="f_y",
                                 label="Frequency Y",
                                 sliderlength=20,
                                 showvalue=0,
                                 from_=0,
                                 to=5,
                                 tickinterval=25)
        self.phase_y = Scale(self.frame,
                             length=250,
                             orient="horizontal",
                             name="p_y",
                             label="Phase Y",
                             sliderlength=20,
                             showvalue=0,
                             from_=0,
                             to=5,
                             tickinterval=25)

        self.frame2 = Frame(parent, bg="black")
        self.varX = IntVar()
        self.varY = IntVar()
        self.varXY = IntVar()
        self.lbl = Label(self.frame2, text="Courbes", fg="black")
        # Boutons de sélection (X, Y ou X-Y)
        self.caseX = Checkbutton(self.frame2,
                                 text="X",
                                 variable=self.varX,
                                 command=self.getX)
        self.caseY = Checkbutton(self.frame2,
                                 text="Y",
                                 variable=self.varY,
                                 command=self.getY)
        self.caseXY = Checkbutton(self.frame2,
                                  text="XY",
                                  variable=self.varXY,
                                  command=self.getXY)

        self.caseXY.select()

        self.wi = self.canvas.cget("width")
        self.hi = self.canvas.cget("height")

        self.stepx = 0
        self.stepy = 0
        # Step x
        self.step_x = Entry(parent, name="x")
        # Step y
        self.step_y = Entry(parent, name="y")

    def update(self, model):
        print("View update")
        if model.getId() == 0:
            signal = model.get_signal()
            self.plot_signal(signal)
        elif model.getId() == 1:
            signal = model.get_signal()
            self.plot_signal(signal, "blue")
        else:
            raise ("Error")

    # Signal X
    def get_magnitude(self, whichOne):
        if whichOne == 0:
            return self.magnitude_x
        elif whichOne == 1:
            return self.magnitude_y
        else:
            raise ("Error")

    def get_frequency(self, whichOne):
        if whichOne == 0:
            return self.frequency_x
        elif whichOne == 1:
            return self.frequency_y
        else:
            raise ("Error")

    def get_phase(self, whichOne):
        if whichOne == 0:
            return self.phase_x
        elif whichOne == 1:
            return self.phase_y
        else:
            raise ("Error")

    def get_step_x(self):
        return self.step_x

    def get_step_y(self):
        return self.step_y

    def getX(self):
        print("update_X(self,event)")
        self.caseY.deselect()
        self.caseXY.deselect()
        self.showX = True
        self.showY = False
        self.update(self.model_x)
        if self.canvas.find_withtag("signal_y"):
            self.canvas.delete("signal_y")

    def getY(self):
        print("update_Y(self,event)")
        self.caseX.deselect()
        self.caseXY.deselect()
        self.showX = False
        self.showY = True
        self.update(self.model_y)
        if self.canvas.find_withtag("signal_x"):
            self.canvas.delete("signal_x")

    def getXY(self):
        print("update_XY(self,event)")
        self.caseX.deselect()
        self.caseY.deselect()
        self.showX = True
        self.showY = True
        self.update(self.model_x)
        self.update(self.model_y)

    def plot_signal(self, signal, color="red"):
        w, h = self.wi, self.hi
        width, height = int(w), int(h)
        if color == "red" and self.showX == True:
            if self.canvas.find_withtag("signal_x"):
                self.canvas.delete("signal_x")
            if signal and len(signal) > 1:
                plot = [(x * width, height / 2.0 * (y + 1))
                        for (x, y) in signal]
                signal_id = self.canvas.create_line(plot,
                                                    fill=color,
                                                    smooth=1,
                                                    width=3,
                                                    tags="signal_x")
        elif color == "blue" and self.showY == True:
            if self.canvas.find_withtag("signal_y"):
                self.canvas.delete("signal_y")
            if signal and len(signal) > 1:
                plot = [(x * width, height / 2.0 * (y + 1))
                        for (x, y) in signal]
                signal_id = self.canvas.create_line(plot,
                                                    fill=color,
                                                    smooth=1,
                                                    width=3,
                                                    tags="signal_y")

    def grid(self, step_x, step_y):
        w, h = self.wi, self.hi
        width, height = int(w), int(h)
        self.stepx = (width - 10) / step_x * 1.
        self.stepy = (height - 10) / step_y * 1.
        for t in range(1, step_x + 2):
            x = t * self.stepx
            self.canvas.create_line(x, 0, x, height, tags="grid")
            #self.canvas.create_line(x,height/2-4,x,height/2+4)
        for t in range(1, step_y + 2):
            y = t * self.stepy
            self.canvas.create_line(0, y, width, y, tags="grid")
            #self.canvas.create_line(width/2-4,y,width/2+4,y)

    def resize(self, event):
        if event:
            self.wi = event.width
            self.hi = event.height

            self.canvas.delete("grid")
            self.plot_signal(self.model_x.get_signal())
            self.plot_signal(self.model_y.get_signal(), "blue")
            self.grid(25, 25)

    def packing(self):
        self.canvas.pack(fill="both", expand=1)
        self.step_x.pack(expand=1, fill="both")
        self.step_y.pack(expand=1, fill="both")
        self.frame.pack(expand=1, fill="both")
        self.magnitude_x.grid(row=0, column=0)
        self.magnitude_y.grid(row=0, column=1)
        self.frequency_x.grid(row=1, column=0)
        self.frequency_y.grid(row=1, column=1)
        self.phase_x.grid(row=2, column=0)
        self.phase_y.grid(row=2, column=1)
        self.frame2.pack(side="bottom", expand=1)
        self.lbl.grid(row=0, column=0)
        self.caseX.grid(row=0, column=1)
        self.caseY.grid(row=0, column=2)
        self.caseXY.grid(row=0, column=3)
コード例 #19
0
ファイル: DBLR_GUI.py プロジェクト: jjgomezcadenas/DBLR
	def initUI(self):

		self.parent.title("DBLR for Dummies")
		self.pack(fill=BOTH, expand=True)

		#self.columnconfigure(0, weight=1)
		#self.rowconfigure(0, weight=1)
		# weight attibute is used to make them growable

		self.meas       = IntVar()
		self.base_path  = StringVar()
		self.coef       = DoubleVar()
		self.noise      = DoubleVar()
		self.n_sigma    = DoubleVar()
		self.thr1       = DoubleVar()
		self.thr2       = DoubleVar()
		self.thr3       = DoubleVar()
		self.graph_sw   = BooleanVar()

		#Image
		factor=0.65
		search = Image.open("NEXT_official_logo.jpg")
		width_org, height_org = search.size		
		search_temp = search.resize((int(width_org*factor), 
							int(height_org*factor)), Image.ANTIALIAS)
		search_aux = ImageTk.PhotoImage(search_temp)
		label1 = Label(self, image=search_aux)
		label1.image = search_aux
		label1.grid(row=0, column=4,
				columnspan=2, rowspan=3, padx=5)


		self.base_path.set("F:/DATOS_DAC/2052/pmt_0_trace_evt_")
		e1 = Entry(self, textvariable=self.base_path, width=40)
		e1.grid(row=0,column=1, sticky=W, columnspan=3, pady=5, padx=5)
		e1_label = Label(self, text="Path & Name")
		e1_label.grid(row=0,column=0, columnspan=1, sticky=E, pady=5, padx=5)

		self.meas.set("1")
		sb1 = Spinbox(self, from_=1, to=100, 
				  width=4, textvariable=self.meas)
		sb1.grid(row=2,column=1, sticky=W, pady=5, padx=5)
		sb1_label = Label(self, text="File")
		sb1_label.grid(row=2,column=0, padx=5, sticky=E)
		
		#Check buttons
		cb1 = Checkbutton(self, text="New Graph", variable=self.graph_sw)
		cb1.select()
		cb1.grid(row=2,column=2, sticky=W)


		#PARAMETERS
		Integration_label = Label(self, text="PARAMETERS",
		                          font = "Verdana 12 bold")
		Integration_label.grid(row=3,column=1,
						padx=5,
						columnspan = 2, pady=10, sticky=E)

		self.coef.set("1.625E-3")
		e2 = Entry(self, width=12, textvariable=self.coef)
		e2.grid(row=4,column=1, sticky=W, pady=5, padx=5)
		e2_label = Label(self, text="DBLR Coef")
		e2_label.grid(row=4,column=0, sticky=E, pady=5, padx=5)

		self.noise.set("0.75")
		e3 = Entry(self, width=12, textvariable=self.noise)
		e3.grid(row=4,column=3, sticky=W, pady=5, padx=5)
		e3_label = Label(self, text="Noise (LSB)")
		e3_label.grid(row=4,column=2, sticky=E, pady=5, padx=5)
		
		self.n_sigma.set("4")
		e4 = Entry(self, width=12, textvariable=self.n_sigma)
		e4.grid(row=4,column=5, sticky=W, pady=5, padx=5)
		e4_label = Label(self, text="Noise Threshold")
		e4_label.grid(row=4,column=4, sticky=E, pady=5, padx=5)

		self.thr1.set("3")
		e5 = Entry(self, width=12, textvariable=self.thr1)
		e5.grid(row=5,column=1, sticky=W, pady=5, padx=5)
		e5_label = Label(self, text="Threshold 1")
		e5_label.grid(row=5,column=0, sticky=E, pady=5, padx=5)

		self.thr2.set("5")
		e6 = Entry(self, width=12, textvariable=self.thr2)
		e6.grid(row=5,column=3, sticky=W, pady=5, padx=5)
		e6_label = Label(self, text="Threshold 2")
		e6_label.grid(row=5,column=2, sticky=E, pady=5, padx=5)

		self.thr3.set("1")
		e7 = Entry(self, width=12, textvariable=self.thr3)
		e7.grid(row=5,column=5, sticky=W, pady=5, padx=5)
		e7_label = Label(self, text="Threshold 3")
		e7_label.grid(row=5,column=4, sticky=E, pady=5, padx=5)





		# Main buttons
		obtn = Button(self, text="GO!!", command=self.DBLR_f)
		obtn.grid(row=6, column=4, sticky=E, pady=10)

		cbtn = Button(self, text="Quit", command=self.quit)
		cbtn.grid(row=6, column=5, sticky=E, pady=10)

		hbtn = Button(self, text="Help", command=self.help_f)
		hbtn.grid(row=6, column=0, sticky=W, pady=10)
コード例 #20
0
class MoveIt(object):
    def __init__(self):
        moveit_commander.roscpp_initialize(sys.argv)  # initialise moveit
        rospy.init_node('lm_move', anonymous=True)  # create a node
        # display_trajectory_publisher = rospy.Publisher(
        #     '/move_group/display_planned_path',
        #     moveit_msgs.msg.DisplayTrajectory,
        #     queue_size=1)  # we don't want to buffer any messages
        # rospy.sleep(10)  # Wait for rviz to initialise
        # rospy.loginfo("\n=[ INFO: Waiting for RVIZ: DONE! ]=\n")

        # This object is an interface to one group of joints.
        self.group = moveit_commander.MoveGroupCommander("manipulator")

        self.group.set_named_target("up")  # go to goal state.
        self.group.go()
        rospy.sleep(2)

        self.robot_initialPos = self.group.get_current_pose().pose.position

        self.subscriber = None  # we need to have the subscriber as an object so we can unregister/register when paused/resumed

        self.resumedRun = False  # flag to determine if it is the first run after pressing 'resume'
        self.paused = True  # flag to determine if program is paused
        self.executing = False  # flag to determine if we are currently executing a plan

        self.prev_desiredPos = geometry_msgs.msg.Pose().position  # keep track of what the previous passed position was
        self.robot_zeroPos = geometry_msgs.msg.Pose().position  # keep track of the robot zero position
        self.hand_zeroPos = geometry_msgs.msg.Pose().position  # keep track of the hand zero position
        self.robot_initialPos = self.robot_initialPos  # keep track of the robot starting position

        self.enableDiffCheck = True  # If enabled will check for difference against a set max before allowing a move
        self.enableBoundaryCheck = True  # If enabled will check if robot is exceeding a boundary

        # boundaries | initial coords: x: 0.603 y: 0.124 z: 0.566
        self.maxLeft = self.robot_initialPos.x - 0.200  # x left
        self.maxRight = self.robot_initialPos.x + 0.200  # x right
        self.maxHeight = self.robot_initialPos.y + 0.300  # y height
        self.maxUp = self.robot_initialPos.z + 0.100  # z up
        self.maxDown = self.robot_initialPos.z - 0.100  # z down

        # maximum step, user cannot move more than this in one step
        self.maxStep = 0.150

        # this is used to round co-ordinates when checking if previous and current coords are very similar
        self.dp = 3  # decimal points

        '''
        -----------------------------------------
            gui_mainWindow
        -----------------------------------------
        '''

        #main GUI window
        self.gui_mainWindow = tk.Tk()
        self.gui_mainWindow.title("LM-Move | Control Panel")
        self.gui_mainWindow.geometry("350x210")
        self.gui_mainWindow.grid_rowconfigure(0, weight=1)
        self.gui_mainWindow.grid_columnconfigure(0, weight=1)
        self.gui_mainWindow.resizable(False, False)

        # current position label
        self.currentPosText = tk.StringVar()
        self.currentPosLabel = tk.Label(self.gui_mainWindow, textvariable=self.currentPosText).grid(row=0, column=0)
        self.currentPosText.set("Current Position\n\nNone!\n")

        # pause button
        self.pauseButtonText = tk.StringVar()
        self.pauseButton = tk.Button(self.gui_mainWindow, textvariable=self.pauseButtonText, command=self.trackingControl, width=20)
        self.pauseButtonText.set("Resume")
        self.pauseButton.configure(bg="green")
        self.pauseButton.grid(row=1, column=0)

        # toggle window button
        self.toggleInfoButton = tk.Button(self.gui_mainWindow, text="Positional Info", command=self.toggleInfoWindow, width=20).grid(row=2, column=0)

        # checkboxes
        self.checkStepBoolVar = tk.BooleanVar()
        self.checkStepBox = Checkbutton(self.gui_mainWindow, text="Robot Overstep Check", variable=self.checkStepBoolVar, width=20, anchor='w')
        self.checkStepBox.select() # check by default
        self.checkStepBox.grid(row=3, column=0)

        self.checkBoundaryBoolVar = tk.BooleanVar()
        self.checkBoundaryBox = Checkbutton(self.gui_mainWindow, text="Robot Boundaries", variable=self.checkBoundaryBoolVar, width=20, anchor='w')
        self.checkBoundaryBox.select() # check by default
        self.checkBoundaryBox.grid(row=4, column=0)

        # error label
        self.errorText = tk.StringVar()
        self.errorLabel = tk.Label(self.gui_mainWindow, textvariable=self.errorText, fg="red").grid(row=5, column=0)
        self.errorText.set("") # there are no errors to begin with

        '''
        -----------------------------------------
            gui_positionInfo
        -----------------------------------------
        '''

        self.gui_positionInfo_hidden = True # keep track if info window is hidden or not

        # new window for zero pos information
        self.gui_positionInfo = tk.Toplevel()
        self.gui_positionInfo.title("LM-Move | Positional Info")
        self.gui_positionInfo.geometry("305x160")
        self.gui_positionInfo.resizable(False, False)
        self.gui_positionInfo.withdraw()

        # robot zero pos label
        self.robot_zeroPosText = tk.StringVar()
        self.robot_zeroPosLabel = tk.Label(self.gui_positionInfo, textvariable=self.robot_zeroPosText).grid(row=0, column=0)
        self.robot_zeroPosText.set("Robot Zero Position\n\nNone!\n")

        # previous robot zero pos label
        self.prev_robot_zeroPosText = tk.StringVar()
        self.prev_robot_zeroPosLabel = tk.Label(self.gui_positionInfo, textvariable=self.prev_robot_zeroPosText).grid(row=1, column=0)
        self.prev_robot_zeroPosText.set("Prev. Robot Zero Position\n\nNone!\n")

        # hand zero pos label
        self.hand_zeroPosText = tk.StringVar()
        self.hand_zeroPosLabel = tk.Label(self.gui_positionInfo, textvariable=self.hand_zeroPosText).grid(row=0, column=1)
        self.hand_zeroPosText.set("Hand Zero Position\n\nNone!\n")

        # previous hand zero pos label
        self.prev_hand_zeroPosText = tk.StringVar()
        self.prev_hand_zeroPosLabel = tk.Label(self.gui_positionInfo, textvariable=self.prev_hand_zeroPosText).grid(row=1, column=1)
        self.prev_hand_zeroPosText.set("Prev. Hand Zero Position\n\nNone!\n")

        # reset zero pos button
        self.resetButton = tk.Button(self.gui_positionInfo, text="Reset Robot Zero Position", command=self.resetZeroPos, width=20)
        self.resetButton.configure(bg="orange")
        self.resetButton.grid(row=2, columnspan=2)

        # subscribe to data
        self.gui_mainWindow.after(1, self.subscribeToTopic)
        # handle closing of GUI
        self.gui_mainWindow.protocol("WM_DELETE_WINDOW", self.onCloseQuit)
        self.gui_positionInfo.protocol("WM_DELETE_WINDOW", self.onCloseHide)
        # keep the GUI running
        self.gui_mainWindow.mainloop()

    # method to begin planning and executing movement of the robot
    def beginPlan(self, hand_pos):
        # check if this is the first run after a resume
        if self.resumedRun:
            # display previous zero positions
            self.prev_robot_zeroPosText.set("Prev. Robot Zero Position\nx: %.3f\ny: %.3f\nz: %.3f" \
                                            % (self.robot_zeroPos.x, self.robot_zeroPos.y, self.robot_zeroPos.z))
            self.prev_hand_zeroPosText.set("Prev. Hand Zero Position\nx: %.3f\ny: %.3f\nz: %.3f" \
                                           % (self.hand_zeroPos.x, self.hand_zeroPos.y, self.hand_zeroPos.z))
            # set the updated zero positions
            self.robot_zeroPos.x = self.group.get_current_pose().pose.position.x
            self.robot_zeroPos.y = self.group.get_current_pose().pose.position.z
            self.robot_zeroPos.z = self.group.get_current_pose().pose.position.y
            self.hand_zeroPos.x = hand_pos.x
            self.hand_zeroPos.y = hand_pos.y
            self.hand_zeroPos.z = hand_pos.z
            # display updated zero positions
            self.hand_zeroPosText.set("Hand Zero Position\nx: %.3f\ny: %.3f\nz: %.3f" \
                                      % (self.hand_zeroPos.x, self.hand_zeroPos.y, self.hand_zeroPos.z))
            self.robot_zeroPosText.set("Robot Zero Position\nx: %.3f\ny: %.3f\nz: %.3f" \
                                       % (self.robot_zeroPos.x, self.robot_zeroPos.y, self.robot_zeroPos.z))
            self.resumedRun = False

        # need to transform leap motion input
        desiredPos = self.getDesiredPos(hand_pos)

        # we round the positions so it is much easier to carry out checks
        prev_desiredPos_x = round(self.prev_desiredPos.x, self.dp)
        desiredPos_x = round(desiredPos.x, self.dp)
        prev_desiredPos_y = round(self.prev_desiredPos.y, self.dp)
        desiredPos_y = round(desiredPos.y, self.dp)
        prev_desiredPos_z = round(self.prev_desiredPos.z, self.dp)
        desiredPos_z = round(desiredPos.z, self.dp)

        '''
        We check 3 things:
        1. If the passed position is very similar to the current one (avoid duplicates)
        2. If the difference is larger than maxDiff (avoid large movements)
        3. If the new position exceeds the boundaries set
        '''

        # check if duplicate
        duplicateCheck = prev_desiredPos_x == desiredPos_x \
                         or prev_desiredPos_y == desiredPos_y \
                         or prev_desiredPos_z == desiredPos_z

        if duplicateCheck:
            # update current position
            self.currentPosText.set("Current Position\nx: %.3f\ny: %.3f\nz: %.3f" \
                                    % (desiredPos.x, desiredPos.y, desiredPos.z))
            # display error
            self.errorText.set("Attempted movement is too similar to previous one!")
            return

        # check if exceeding boundaries
        boundaryCheck_x = desiredPos_x > self.maxRight \
                          or desiredPos_x < self.maxLeft
        boundaryCheck_y = desiredPos_y > self.maxHeight
        boundaryCheck_z = desiredPos_z > self.maxUp \
                          or desiredPos_z < self.maxDown

        # if any of the checks are true and the checkbox is currently checked
        if (boundaryCheck_x or boundaryCheck_y or boundaryCheck_z) and self.checkBoundaryBoolVar.get():
            # update current position with additional info of what axis reached boundary
            self.currentPosText.set("Current Position\nx: %.3f | %s \ny: %.3f | %s\nz: %.3f | %s" \
                                    % (desiredPos.x, boundaryCheck_x, desiredPos.y, boundaryCheck_y, desiredPos.z,
                                       boundaryCheck_z))
            # display error
            self.errorText.set("Boundaries reached!")
            return

        # check if difference between previous and current attempt is too high (overstep)
        prevPosArray = [prev_desiredPos_x, prev_desiredPos_y, prev_desiredPos_z]
        # avoid checking if there is no previous position
        if any(x > 0.0 for x in prevPosArray):
            stepCheck_x = abs(prev_desiredPos_x - desiredPos_x) > self.maxStep
            stepCheck_y = abs(prev_desiredPos_y - desiredPos_y) > self.maxStep
            stepCheck_z = abs(prev_desiredPos_z - desiredPos_z) > self.maxStep
            # if any of the checks are true and the checkbox is currently checked
            if (stepCheck_x or stepCheck_y or stepCheck_z) and self.checkStepBoolVar.get():
                # update current position with additional info of what axis has overstepped
                self.currentPosText.set("Current Position\nx: %.3f | %s \ny: %.3f | %s\nz: %.3f | %s" \
                                        % (desiredPos.x, stepCheck_x, desiredPos.y, stepCheck_y, desiredPos.z,
                                           stepCheck_z))
                # display error
                self.errorText.set("Overstep detected!")
                return

        # clear any previous error set as in this run all checks are false
        self.errorText.set("")
        # we are now executing
        self.executing = True
        # keep track of previous position
        self.prev_desiredPos.x = desiredPos.x
        self.prev_desiredPos.y = desiredPos.y
        self.prev_desiredPos.z = desiredPos.z
        # all checks equate to false thus this is a valid attempt, log this
        rospy.loginfo("\n===> ATTEMPTING -> x: %.3f | y: %.3f | z: %.3f" % (desiredPos.x, desiredPos.y, desiredPos.z))
        # update the current position
        self.currentPosText.set(
            "Current Position\nx: %.3f\ny: %.3f\nz: %.3f" % (desiredPos.x, desiredPos.y, desiredPos.z))

        # append current pose to the waypoints array
        waypoints = []
        waypoints.append(self.group.get_current_pose().pose)
        # set the pose for x, y and z
        wpose = geometry_msgs.msg.Pose()
        wpose.position.x = desiredPos.x
        wpose.position.y = desiredPos.z  # we switch z and y because the leap motion is faced upwards
        wpose.position.z = desiredPos.y
        waypoints.append(copy.deepcopy(wpose))
        # plan the movement
        (plan, fraction) = self.group.compute_cartesian_path(
            waypoints,  # waypoints to follow
            0.01,  # eef_step
            0.0)  # jump_threshold
        # execute the plan
        self.group.execute(plan)
        # we are no longer executing
        self.executing = False

    # method to begin sending information to the planner
    def beginExecution(self, leap_msg):
        if not self.executing and not self.paused:
            # store xyz information in a variable
            palmPos = leap_msg.palmpos
            # create an array of the xyz
            posArray = [palmPos.x, palmPos.y, palmPos.z]
            # check if x,y,z is > than 0.0 (avoid passing 0.0 coordinates)
            if any(x > 0.0 for x in posArray):
                self.beginPlan(palmPos)

    # method to get the desired position of the robot
    def getDesiredPos(self, hand_pos):
        # lower leap motion values by this much
        conversion_value = 0.001
        # adjust the offset and pass back the new coordinates
        desired_pos = geometry_msgs.msg.Pose().position
        desired_pos.x = self.robot_zeroPos.x - ((hand_pos.x - self.hand_zeroPos.x) * conversion_value)  # inverted
        desired_pos.y = self.robot_zeroPos.y + ((hand_pos.y - self.hand_zeroPos.y) * conversion_value)
        desired_pos.z = self.robot_zeroPos.z + ((hand_pos.z - self.hand_zeroPos.z) * conversion_value)
        return desired_pos

    # method to subscribe to the ros topic
    def subscribeToTopic(self):
        # register to the topic
        self.subscriber = rospy.Subscriber("/leapmotion/data", leapros, self.beginExecution, queue_size=1)

    # method for pausing/unpausing the tracking of the users hand
    def trackingControl(self, *ignore):
        if self.paused:
            # adjust button text/colour
            self.pauseButtonText.set("Pause")
            self.pauseButton.configure(bg="yellow")
            # adjust flags
            self.paused = False
            self.resumedRun = True
            # register back to the topic
            self.subscribeToTopic()
        else:
            # unregister from the topic
            self.subscriber.unregister()
            # adjust button text/colour
            self.pauseButtonText.set("Resume")
            self.pauseButton.configure(bg="green")
            # adjust flag
            self.paused = True
            # if we are paused we don't want to see errors
            self.errorText.set("")

    # action method for pressing the "reset zero position" button
    def resetZeroPos(self, *ignore):
        if not self.paused:
            self.robot_zeroPos.x = self.robot_initialPos.x
            self.robot_zeroPos.y = self.robot_initialPos.y
            self.robot_zeroPos.z = self.robot_initialPos.z
            self.robot_zeroPosText.set("Zero Position\nx: %.3f\ny: %.3f\nz: %.3f" % (
            self.robot_zeroPos.x, self.robot_zeroPos.y, self.robot_zeroPos.z))
            tkMessageBox.showinfo("Information", "Zero position has been reset")
        else:
            tkMessageBox.showerror("Error", "Cannot reset zero position because the program is currently paused")

    # action method for toggling the info window popup when pressing the button
    def toggleInfoWindow(self, *ignore):
        if self.gui_positionInfo_hidden:
            self.gui_positionInfo.deiconify()
            self.gui_positionInfo_hidden = False
        else:
            self.gui_positionInfo.withdraw()
            self.gui_positionInfo_hidden = True

    # action method for hiding a window upon clicking [x]
    def onCloseHide(self, *ignore):
        self.gui_positionInfo.withdraw()
        self.gui_positionInfo_hidden = True

    # action method for quitting the program upon clicking [x]
    def onCloseQuit(self, *ignore):
        if tkMessageBox.askokcancel("Quit", "Do you want to quit?"):
            self.gui_mainWindow.destroy()
コード例 #21
0
ファイル: gui.py プロジェクト: imcj/pybbs
    def init_gui(self):
        """init helper"""
        #setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        #Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lbMessages = Listbox(msg_frame,
                  yscrollcommand=rightscrollbar.set,
                  xscrollcommand=bottomscrollbar.set,
                  bg="white")
        self.lbMessages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lbMessages.yview)
        bottomscrollbar.config(command=self.lbMessages.xview)

        #History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(history_frame,
                    yscrollcommand=rightscrollbar2.set,
                    xscrollcommand=bottomscrollbar2.set,
                    bg="white")
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind('<Double-Button-1>', self.select_recent_file)
        self.set_history_window()

        #status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        #labels
        self.lblRatingLabel = Label(rating_frame, text='Rating:')
        self.lblRatingLabel.pack(side=LEFT)
        self.lblRating = Label(rating_frame, textvariable=self.rating)
        self.lblRating.pack(side=LEFT)
        Label(mid_frame, text='Recently Used:').pack(side=LEFT)
        Label(top_frame, text='Module or package').pack(side=LEFT)

        #file textbox
        self.txtModule = Entry(top_frame, background='white')
        self.txtModule.bind('<Return>', self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)

        #results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(res_frame,
                  yscrollcommand=rightscrollbar.set,
                  xscrollcommand=bottomscrollbar.set,
                  bg="white", font="Courier")
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        #buttons
        Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
        Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)

        #radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window)
        c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window)
        r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window)
        w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window)
        e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window)
        f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window)
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        #check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window)
        rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window)
        dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window)
        ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window)
        stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window)
        msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window)
        msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window)
        report.select()
        report.grid(column=0, row=0, sticky=W)
        rawMet.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=E)
        stat.grid(column=0, row=1, sticky=W)
        msgCat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, columnspan=2, sticky=W)

        #dictionary for check boxes and associated error term
        self.msg_type_dict = {
            'I' : lambda : self.information_box.get() == 1,
            'C' : lambda : self.convention_box.get() == 1,
            'R' : lambda : self.refactor_box.get() == 1,
            'E' : lambda : self.error_box.get() == 1,
            'W' : lambda : self.warning_box.get() == 1,
            'F' : lambda : self.fatal_box.get() == 1
        }
        self.txtModule.focus_set()
コード例 #22
0
class Pref_Screen(Frame):
    '''
    Frame for Preferences screen.
    '''
    def sall(self):
        '''
        On CLick Select All button
        '''
        n = len(online_courses)
        for i in range(0, n):
            courseboxes[i].checkbox.select()

    def dall(self):
        '''
        On CLick Deselect All button
        '''
        n = len(online_courses)
        for i in range(0, n):
            courseboxes[i].checkbox.deselect()

    def save(self):
        '''
        On CLick Save Settings button
        '''
        #Saves courseboxes and online_courses data to Preferences
        open('Preferences', 'w').close()
        preferences = open('Preferences', 'w')
        for i in range(0, len(online_courses)):
            x = str(courseboxes[i].directory.get())
            if not x.endswith('/'):
                courseboxes[i].directory.set(x + '/')
            preferences.write(str(courseboxes[i].var.get()) + '\n')
            preferences.write(online_courses[i].name + '\n')
            preferences.write(online_courses[i].mainlink + '\n')
            preferences.write(courseboxes[i].directory.get() + '\n')
            preferences.write(online_courses[i].nflink + '\n')
            preferences.write(str(online_courses[i].lastmain) + '\n')
            preferences.write(str(online_courses[i].lastnf) + '\n')
            courseboxes[i].pack_forget()

        preferences.close()

        #Go to Home screen
        self.frame.destroy()
        self.newWindow = Home(m)

        #Save root directory address to Cred
        creds = open('Cred', 'r')
        lines = creds.readlines()
        creds.close()

        creds = open('Cred', 'w')
        lines[3] = self.root_dir_box.directory.get() + '\n'
        lines[4] = str(self.auto.get()) + '\n'

        creds.writelines(lines)
        creds.close()

        #Add key to registry for startup launch
        if self.auto.get() == 1:
            add_to_startup()
        #Remove key from registry for starup launch
        else:
            remove_from_startup()

    def load_online_courses(self):
        '''
        Finds all links for course main pages and creates course_object objects
        '''
        br.open('http://moodle.iitb.ac.in/')

        for link in br.links(
                url_regex='http://moodle.iitb.ac.in/course/view.php'):
            online_courses.append(course_object(link.url, link.text))

    def update_from_preferences(self, n):
        '''
        Finds courses from Preferences and updates parameters
        for corresponding course in online_courses
        '''

        if os.path.exists('Preferences'):
            file_pref = open('Preferences', 'r')
            lines = file_pref.readlines()
            TotalInPreferences = len(lines) / 7
            if len(lines):
                for number in range(0, TotalInPreferences):
                    for i in range(0, n):
                        if online_courses[i].mainlink in lines[7 * number + 2]:
                            online_courses[i].directory = lines[7 * number + 3]\
                                                        [:lines[7 * number + 3].index('\n')]
                            online_courses[i].chkbox = lines[7 * number]\
                                                     [:lines[7 * number].index('\n')]
                            online_courses[i].nflink = lines[7 * number + 4]\
                                                     [:lines[7 * number + 4].index('\n')]
                            break

        #get_nf_link for all courses that don't have an nflink
        for i in range(0, n):
            if online_courses[i].nflink is "":
                online_courses[i].get_nf_link()

    def __init__(self, master):

        global myname
        del courseboxes[:]
        del online_courses[:]

        self.load_online_courses()
        n = len(online_courses)

        self.update_from_preferences(n)

        self.frame = ScrollableFrame(m)

        self.frame.pack(fill=Tkinter.BOTH, expand=Tkinter.TRUE)

        self.root_dir_box = box(self.frame)

        #Create checkbox, label and browse button for all courses
        for i in range(0, n):
            courseboxes.append(box(self.frame, i))

        self.selectall = Button(self.frame.interior,
                                text='Select All',
                                command=self.sall)
        self.selectall.grid(row=0, column=0, pady=10)
        self.deselectall = Button(self.frame.interior,
                                  text='Deselect All',
                                  command=self.dall)
        self.deselectall.grid(row=0, column=1, padx=[0, 100], pady=10)
        self.save = Button(self.frame.interior,
                           text='Save Settings',
                           command=self.save)
        self.save.grid(row=0, column=2, pady=10)

        self.auto = IntVar()
        self.autoDLD = Checkbutton(self.frame.interior,
                                   text="Auto-Download",
                                   width=20,
                                   variable=self.auto)
        self.autoDLD.grid(row=0, column=0, sticky="w")

        if os.path.exists('Cred'):
            file_pref = open('Cred', 'r')
            lines = file_pref.readlines()
            if len(lines) > 4:
                x = lines[4].replace('\n', '')
                if x == '1':
                    self.autoDLD.select()

        self.f = Frame(self.frame.interior, height=20)
        self.f.grid(row=2, columnspan=3, sticky="we")
コード例 #23
0
class SignalSelected(Frame):
    """
    Selection signal : Y, X ou XY

   """
    def __init__(self, parent):
        Frame.__init__(self)
        self.configure(bd=1, relief="sunken")
        self.parent = parent

        #Choix affichage X, Y ou XY
        self.X = IntVar()
        self.Y = IntVar()
        self.XY = IntVar()

        self.XCheckBox = Checkbutton(self,
                                     text="Courbe X",
                                     command=self.updateX,
                                     variable=self.X,
                                     onvalue=1,
                                     offvalue=0,
                                     height=5,
                                     width=20)

        self.YCheckBox = Checkbutton(self,
                                     text="Courbe Y",
                                     onvalue=1,
                                     offvalue=0,
                                     variable=self.Y,
                                     height=5,
                                     width=20,
                                     command=self.updateY)

        self.XYCheckBox = Checkbutton(self,
                                      text="Courbe XY",
                                      onvalue=1,
                                      offvalue=0,
                                      variable=self.XY,
                                      height=5,
                                      width=20,
                                      command=self.updateXY)

        self.XCheckBox.select()
        self.YCheckBox.select()

        self.XCheckBox.pack(fill="both", expand="yes")
        self.YCheckBox.pack(fill="both", expand="yes")
        self.XYCheckBox.pack(fill="both", expand="yes")

    def updateX(self):
        if self.X.get():
            self.parent.view.signal_X_allowed = 1
            self.parent.control_X.update_signal(None)
        else:
            self.parent.view.signal_X_allowed = 0
            self.parent.view.delete(self.parent.view.signal_X)

    def updateY(self):
        if self.Y.get():
            self.parent.view.signal_Y_allowed = 1
            self.parent.control_Y.update_signal(None)
        else:
            self.parent.view.signal_Y_allowed = 0
            self.parent.view.delete(self.parent.view.signal_Y)

    def updateXY(self):
        if self.XY.get():
            self.parent.control_L.signal_XY_allowed = 1
            self.parent.view.plot_signal('X-Y')
        else:
            self.parent.control_L.signal_XY_allowed = 0
            self.parent.control_L.delete(self.parent.view.signal_XY)
コード例 #24
0
class Generator(Frame):
    """
    Vibration harmonique du type : e=a*sin(2*pi*f*t+p)

    scale_A : controleur d'Amplitude
    scale_F : controleur de Frequence
    scale_P : controleur de Phase

    """
    def __init__(self, parent, name="X"):
        """
        Initialisation

        parent : un oscilloscope
        name : nom du signal
        """
        Frame.__init__(self)
        self.configure(bd=1, relief="sunken")
        self.parent = parent
        self.name = name
        self.drawVar = IntVar()
        self.signal = None

        self.draw = Checkbutton(self,
                                text="Afficher " + self.name,
                                selectcolor=eval('self.parent.view.color_' +
                                                 name),
                                variable=self.drawVar,
                                onvalue=1,
                                offvalue=0,
                                command=self.parent.plot_all)
        self.draw.pack()
        self.draw.select()

        self.scale_A = Scale(self,
                             length=100,
                             orient="horizontal",
                             label=name + " Amplitude",
                             showvalue=1,
                             from_=0,
                             to=10,
                             tickinterval=1,
                             command=self.update_signal)
        self.scale_A.pack(expand="yes", fill="both")

        self.scale_F = Scale(self,
                             length=100,
                             orient="horizontal",
                             label=name + " Fréquence",
                             showvalue=1,
                             from_=1,
                             to=10,
                             tickinterval=1,
                             command=self.update_signal)
        self.scale_F.pack(expand="yes", fill="both")

        self.scale_P = Scale(self,
                             length=100,
                             orient="horizontal",
                             label=name + " Phase",
                             showvalue=1,
                             from_=0,
                             to=10,
                             tickinterval=1,
                             command=self.update_signal)
        self.scale_P.pack(expand="yes", fill="both")

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

    def update_signal(self, event):
        """
        Mise a jour de signal si modifications (amplitude, frequence, phase)
        """
        print("Vibration.update_signal()")
        print("Amplitude :", self.scale_A.get())
        scaling = 0.05
        amp = scaling * self.scale_A.get()
        signal = self.generate_signal(a=amp,
                                      f=self.scale_F.get(),
                                      p=self.scale_P.get())
        self.signal = signal
        if not isinstance(self.parent, Tk):
            self.parent.update_view(self.name, signal)
        self.parent.plot_all()
        return signal

    def generate_signal(self, a=1.0, f=2.0, p=0):
        """
        Calcul de l'elongation : e=a*sin(2*pi*f*t+p) sur une periode
        a : amplitude
        f : frequence
        p : phase
        """
        signal = []
        samples = 1000
        for t in range(0, samples):
            samples = float(samples)
            e = a * sin((2 * pi * f * (t / samples)) - p)
            signal.append((t / samples, e))
        return signal
コード例 #25
0
ファイル: mod_win_edit_bp.py プロジェクト: prospero78/pyPC
class ClsWinEditBP(ClsTopWin):
    """
    Окно редактирования свойств регистра ВР.
    """
    def __init__(self, root=None):
        """
        Создаёт окно регистра программного прерывания.
        :param root:
        :return:
        """

        def create_frm_up():
            """
            Создание фрейма верхней части.
            :return:
            """
            self.frm_up = Frame(self, border=3, relief='groove')
            self.frm_up.pack(fill='both', expand=1, side='top')

            self.lbl_reg_pc = Label(self.frm_up,
                                    border=3,
                                    relief='raised',
                                    text=' reg_pc ',
                                    bg='white',
                                    fg='red',
                                    font='Arial 24 bold')
            self.lbl_reg_pc.pack(side='left', fill='y')
            # --------------------------------------------------------------
            self.frm_adr_break = Frame(self.frm_up, border=3, relief='groove')
            self.frm_adr_break.pack(fill='x', side='top')

            self.lbl_adr_break = Label(self.frm_adr_break,
                                       text='adr_break',
                                       relief='raised')
            self.lbl_adr_break.pack(side='top', fill='x')

            self.ent_adr_break_val = Entry(self.frm_adr_break, cursor='hand2')
            self.ent_adr_break_val.pack(side='top', fill='x')

            self.ent_adr_break_val.insert(0, '0')
            #--------------------------------------------------------------
            self.frm_adr_proc = Frame(self.frm_up, border=3, relief='groove')
            self.frm_adr_proc.pack(fill='x', side='top')

            self.lbl_adr_proc = Label(self.frm_adr_proc,
                                      text='adr_proc',
                                      relief='raised')
            self.lbl_adr_proc.pack(side='top', fill='x')

            self.ent_adr_proc_val = Entry(self.frm_adr_proc, cursor='hand2')
            self.ent_adr_proc_val.pack(side='top', fill='x')

            self.ent_adr_proc_val.insert(0, '0')
            #--------------------------------------------------------------
            self.frm_act = Frame(self.frm_up, border=3, relief='groove')
            self.frm_act.pack(fill='both', expand=1, side='top')

            self.lbl_act = Label(self.frm_act, text='flag_act', relief='raised')
            self.lbl_act.pack(side='top', fill='x')

            self.flag_act = IntVar()
            self.chek_act_val = Checkbutton(self.frm_act,
                                            cursor='hand2',
                                            state='active',
                                            text='active register',
                                            variable=self.flag_act)
            self.chek_act_val.select()
            self.chek_act_val.pack(side='top', fill='x')

        def create_frm_btn():
            """
            Создание фрейма кнопок.
            :return:
            """
            self.frm_btn = Frame(self, border=3, relief='raised')
            self.frm_btn.pack(side='bottom', fill='x')

            self.btn_close = Button(self.frm_btn,
                                    text=self.lang['win_edit_bp_btn_close'],
                                    bg='gray',
                                    command=self.destroy)
            self.btn_close.pack(side='right')

        self.__root = root
        self.lang = root.res.lang_str.lang_dict
        self.ent_adr_break_val = None
        self.frm_up = None
        self.frm_adr_break = None
        self.flag_act = None
        self.ent_adr_proc_val = None
        self.frm_btn = None
        self.frm_adr_proc = None
        self.lbl_act = None
        self.lbl_reg_pc = None
        self.lbl_adr_proc = None
        self.chek_act_val = None
        self.frm_act = None
        self.btn_close = None
        self.lbl_adr_break = None

        ClsTopWin.__init__(self, title=self.lang['win_edit_bp_title'])
        create_frm_up()
        create_frm_btn()


    def destroy(self):
        """
        Скрытие окна регистра программного прерывания.
        :return:
        """
        ClsTopWin.destroy(self)
        self.__root.control.win_edit_bp_hide()
コード例 #26
0
ファイル: cockpit.py プロジェクト: dpm76/eaglebone
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()
コード例 #27
0
ファイル: MooDLD.py プロジェクト: CodeMaxx/MooDLD
class Pref_Screen(Frame):

    '''
    Frame for Preferences screen.
    '''

    def sall(self):
        '''
        On CLick Select All button
        '''
        n = len(online_courses)
        for i in range(0, n):
            courseboxes[i].checkbox.select()

    def dall(self):
        '''
        On CLick Deselect All button
        '''
        n = len(online_courses)
        for i in range(0, n):
            courseboxes[i].checkbox.deselect()

    def save(self):
        '''
        On CLick Save Settings button
        '''
        #Saves courseboxes and online_courses data to Preferences
        open('Preferences', 'w').close()
        preferences = open('Preferences', 'w')
        for i in range(0, len(online_courses)):
            x = str(courseboxes[i].directory.get())
            if not x.endswith('/'):
                courseboxes[i].directory.set(x + '/')
            preferences.write(str(courseboxes[i].var.get()) + '\n')
            preferences.write(online_courses[i].name + '\n')
            preferences.write(online_courses[i].mainlink + '\n')
            preferences.write(courseboxes[i].directory.get() + '\n')
            preferences.write(online_courses[i].nflink + '\n')
            preferences.write(str(online_courses[i].lastmain) + '\n')
            preferences.write(str(online_courses[i].lastnf) + '\n')
            courseboxes[i].pack_forget()

        preferences.close()

        #Go to Home screen
        self.frame.destroy()
        self.newWindow = Home(m)

        #Save root directory address to Cred
        creds = open('Cred', 'r')
        lines = creds.readlines()
        creds.close()

        creds = open('Cred', 'w')
        lines[3] = self.root_dir_box.directory.get() + '\n'
        lines[4] = str(self.auto.get()) + '\n'

        creds.writelines(lines)
        creds.close()

        #Add key to registry for startup launch
        if self.auto.get() == 1:
            add_to_startup()
        #Remove key from registry for starup launch
        else:
            remove_from_startup()

    def load_online_courses(self):
        '''
        Finds all links for course main pages and creates course_object objects
        '''
        br.open('http://moodle.iitb.ac.in/')

        for link in br.links(url_regex='http://moodle.iitb.ac.in/course/view.php'):
            online_courses.append(course_object(link.url, link.text))

    def update_from_preferences(self, n):
        '''
        Finds courses from Preferences and updates parameters
        for corresponding course in online_courses
        '''

        if os.path.exists('Preferences'):
            file_pref = open('Preferences', 'r')
            lines = file_pref.readlines()
            TotalInPreferences = len(lines) / 7
            if len(lines):
                for number in range(0, TotalInPreferences):
                    for i in range(0, n):
                        if online_courses[i].mainlink in lines[7 * number + 2]:
                            online_courses[i].directory = lines[7 * number + 3]\
                                                        [:lines[7 * number + 3].index('\n')]
                            online_courses[i].chkbox = lines[7 * number]\
                                                     [:lines[7 * number].index('\n')]
                            online_courses[i].nflink = lines[7 * number + 4]\
                                                     [:lines[7 * number + 4].index('\n')]
                            break

        #get_nf_link for all courses that don't have an nflink
        for i in range(0, n):
            if online_courses[i].nflink is "":
                online_courses[i].get_nf_link()

    def __init__(self, master):

        global myname
        del courseboxes[:]
        del online_courses[:]

        self.load_online_courses()
        n = len(online_courses)

        self.update_from_preferences(n)

        self.frame = ScrollableFrame(m)

        self.frame.pack(fill=Tkinter.BOTH, expand=Tkinter.TRUE)

        self.root_dir_box = box(self.frame)

        #Create checkbox, label and browse button for all courses
        for i in range(0, n):
            courseboxes.append(box(self.frame, i))

        self.selectall = Button(self.frame.interior, text='Select All',
                                command=self.sall)
        self.selectall.grid(row=0, column=0, pady=10)
        self.deselectall = Button(self.frame.interior,
                                  text='Deselect All',
                                  command=self.dall)
        self.deselectall.grid(row=0, column=1, padx=[0, 100], pady=10)
        self.save = Button(self.frame.interior, text='Save Settings',
                           command=self.save)
        self.save.grid(row=0, column=2, pady=10)

        self.auto = IntVar()
        self.autoDLD = Checkbutton(self.frame.interior, text="Auto-Download", width=20,
                                   variable=self.auto)
        self.autoDLD.grid(row=0, column=0, sticky="w")

        if os.path.exists('Cred'):
            file_pref = open('Cred', 'r')
            lines = file_pref.readlines()
            if len(lines) > 4:
                x = lines[4].replace('\n', '')
                if x == '1':
                    self.autoDLD.select()

        self.f = Frame(self.frame.interior, height=20)
        self.f.grid(row=2, columnspan=3, sticky="we")
コード例 #28
0
class Generator(Frame):
    """
    Vibration harmonique du type : e=a*sin(2*pi*f*t+p)

    scale_A : controleur d'Amplitude
    scale_F : controleur de Frequence
    scale_P : controleur de Phase

    """
    def __init__(self, parent, name="X"):
        """
        Initialisation

        parent : un oscilloscope
        name : nom du signal
        """
        Frame.__init__(self)
        self.configure(bd=1, relief="sunken")
        self.parent = parent
        self.name = name
        self.drawVar = IntVar()
        self.signal = None

        self.draw = Checkbutton(self,text="Afficher "+self.name, selectcolor=eval('self.parent.view.color_'+name), variable=self.drawVar, onvalue = 1, offvalue = 0, command=self.parent.plot_all)
        self.draw.pack()
        self.draw.select()

        self.scale_A = Scale(self, length=100, orient="horizontal",
                label=name + " Amplitude", showvalue=1, from_=0, to=10,
                tickinterval=1, command=self.update_signal)
        self.scale_A.pack(expand="yes", fill="both")

        self.scale_F = Scale(self, length=100, orient="horizontal",
                label=name + " Fréquence", showvalue=1, from_=1, to=10,
                tickinterval=1, command=self.update_signal)
        self.scale_F.pack(expand="yes", fill="both")

        self.scale_P = Scale(self, length=100, orient="horizontal",
                label=name + " Phase", showvalue=1, from_=0, to=10,
                tickinterval=1, command=self.update_signal)
        self.scale_P.pack(expand="yes", fill="both")

        
        self.bind("<Configure>",self.update_signal)
        
    def update_signal(self, event):
        """
        Mise a jour de signal si modifications (amplitude, frequence, phase)
        """
        print("Vibration.update_signal()")
        print("Amplitude :", self.scale_A.get())
        scaling=0.05
        amp = scaling*self.scale_A.get()
        signal = self.generate_signal(a=amp,f=self.scale_F.get(),
                                      p=self.scale_P.get())
        self.signal = signal
        if not isinstance(self.parent, Tk):
            self.parent.update_view(self.name, signal)
        self.parent.plot_all()
        return signal

    def generate_signal(self, a=1.0, f=2.0, p=0):
        """
        Calcul de l'elongation : e=a*sin(2*pi*f*t+p) sur une periode
        a : amplitude
        f : frequence
        p : phase
        """
        signal = []
        samples = 1000
        for t in range(0, samples):
            samples = float(samples)
            e = a * sin((2*pi*f*(t/samples)) - p)
            signal.append((t/samples,e))
        return signal
コード例 #29
0
ファイル: MooDLD.py プロジェクト: CodeMaxx/MooDLD
class box(Frame):
    '''
    Class for box object having checkbox, label, browsebutton
    '''

    def getdir(self):
        '''
        On click for browse button of courses
        '''
        directory = tkFileDialog.askdirectory(parent=m, initialdir='C:/',
                                              title='Please select a directory')
        if len(directory) > 0:
            self.directory.set(directory)

    def rootgetdir(self):
        '''
        On click for browse button for Root directory
        '''
        directory = tkFileDialog.askdirectory(parent=m, initialdir='C:/',
                                              title='Please select a directory')
        if len(directory) > 0:
            self.directory.set(directory)
            for i in range(len(courseboxes)):
                courseboxes[i].directory.set(directory +'/' + online_courses[i].name[:6])
        else:
            self.directory.set('C:/')

    def __init__(self, master, number=None):
        Frame.__init__(self)
        self.var = IntVar()

        #For courseboxes
        if number is not None:
            self.directory = StringVar()
            self.checkbox = Checkbutton(master.interior,
                                        text=online_courses[number].name, width=60,
                                        variable=self.var, anchor="w")
            self.checkbox.grid(row=number + 3, column=0, padx=5)
            self.browse = Button(master.interior, text='Browse',
                                 command=self.getdir)
            self.browse.grid(row=number + 3, column=1)

            if online_courses[number].chkbox == '1':
                self.checkbox.select()
            self.directory.set(online_courses[number].directory)
            self.label_dir = Label(master.interior,
                                   textvariable=self.directory)
            self.label_dir.grid(row=number + 3, column=2)

        #For root_dir_box
        else:
            self.directory = StringVar()
            self.label = Label(master.interior,
                               text='Root Directory', width=60)
            self.label.grid(row=1, column=0)
            self.browse = Button(master.interior, text='Browse',
                                 command=self.rootgetdir)
            self.browse.grid(row=1, column=1)

            if os.path.exists('Cred'):
                file_pref = open('Cred', 'r')
                lines = file_pref.readlines()
                if len(lines) > 4:
                    self.directory.set(lines[3].replace('\n', ''))
                else:
                    self.directory.set('C:/')
            else:
                self.directory.set('C:/')

            self.label_dir = Label(master.interior, textvariable=self.directory)
            self.label_dir.grid(row=1, column=2)
コード例 #30
0
class box(Frame):
    '''
    Class for box object having checkbox, label, browsebutton
    '''
    def getdir(self):
        '''
        On click for browse button of courses
        '''
        directory = tkFileDialog.askdirectory(
            parent=m, initialdir='C:/', title='Please select a directory')
        if len(directory) > 0:
            self.directory.set(directory)

    def rootgetdir(self):
        '''
        On click for browse button for Root directory
        '''
        directory = tkFileDialog.askdirectory(
            parent=m, initialdir='C:/', title='Please select a directory')
        if len(directory) > 0:
            self.directory.set(directory)
            for i in range(len(courseboxes)):
                courseboxes[i].directory.set(directory + '/' +
                                             online_courses[i].name[:6])
        else:
            self.directory.set('C:/')

    def __init__(self, master, number=None):
        Frame.__init__(self)
        self.var = IntVar()

        #For courseboxes
        if number is not None:
            self.directory = StringVar()
            self.checkbox = Checkbutton(master.interior,
                                        text=online_courses[number].name,
                                        width=60,
                                        variable=self.var,
                                        anchor="w")
            self.checkbox.grid(row=number + 3, column=0, padx=5)
            self.browse = Button(master.interior,
                                 text='Browse',
                                 command=self.getdir)
            self.browse.grid(row=number + 3, column=1)

            if online_courses[number].chkbox == '1':
                self.checkbox.select()
            self.directory.set(online_courses[number].directory)
            self.label_dir = Label(master.interior,
                                   textvariable=self.directory)
            self.label_dir.grid(row=number + 3, column=2)

        #For root_dir_box
        else:
            self.directory = StringVar()
            self.label = Label(master.interior,
                               text='Root Directory',
                               width=60)
            self.label.grid(row=1, column=0)
            self.browse = Button(master.interior,
                                 text='Browse',
                                 command=self.rootgetdir)
            self.browse.grid(row=1, column=1)

            if os.path.exists('Cred'):
                file_pref = open('Cred', 'r')
                lines = file_pref.readlines()
                if len(lines) > 4:
                    self.directory.set(lines[3].replace('\n', ''))
                else:
                    self.directory.set('C:/')
            else:
                self.directory.set('C:/')

            self.label_dir = Label(master.interior,
                                   textvariable=self.directory)
            self.label_dir.grid(row=1, column=2)
コード例 #31
0
class BoardConfigAdvance(Frame):

    def __init__(self, master=None, main=None):
        Frame.__init__(self, master)

        self.parent = master
        self.main = main

        self.parent.geometry("280x174")
        self.parent.title(os.getenv("NAME") + " - Advance Board Config")
        self.master.configure(padx=10, pady=10)

        self.HEAPSIZE = {"512 byte": 512,
                         "1024 byte": 1024,}
        self.OPTIMIZATION = "-O2 -O3 -Os".split()

        self.mips16_var = IntVar()
        self.checkBox_mips16 = Checkbutton(self.parent, text="Mips16", anchor="w", variable=self.mips16_var)
        self.checkBox_mips16.pack(expand=True, fill=BOTH, side=TOP)

        frame_heap = Frame(self.parent)
        Label(frame_heap, text="Heap size:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True)
        self.comboBox_heapsize = Combobox(frame_heap, values=self.HEAPSIZE.keys())
        self.comboBox_heapsize.pack(fill=X, expand=True, side=RIGHT)
        frame_heap.pack(fill=X, expand=True, side=TOP)

        frame_opt = Frame(self.parent)
        Label(frame_opt, text="Optimization:", anchor="w", width=12).pack(side=LEFT, fill=X, expand=True)
        self.comboBox_optimization = Combobox(frame_opt, values=self.OPTIMIZATION)
        self.comboBox_optimization.pack(fill=X, expand=True, side=RIGHT)
        frame_opt.pack(fill=X, expand=True, side=TOP)

        frame_buttons = Frame(self.parent)
        Button(frame_buttons, text="Accept", command=self.accept_config).pack(fill=X, expand=True, side=LEFT)
        Button(frame_buttons, text="Restore Default", command=self.restore_default).pack(fill=X, expand=True, side=RIGHT)
        frame_buttons.pack(fill=X, expand=True, side=BOTTOM)

        self.load_config()


    #----------------------------------------------------------------------
    def quit(self):

        self.master.destroy()



    #----------------------------------------------------------------------
    def load_config(self):

        #Called in the parent frame
        #self.main.configIDE.load_config()

        if self.main.configIDE.config("Board", "mips16", True):
            self.checkBox_mips16.select()
        else:
            self.checkBox_mips16.deselect()

        heapsize = self.main.configIDE.config("Board", "heapsize", 512)
        for key in self.HEAPSIZE.keys():
            if self.HEAPSIZE[key] == heapsize:
                self.comboBox_heapsize.set(key)
                break

        optimization = self.main.configIDE.config("Board", "optimization", "-O3")
        self.comboBox_optimization.set(optimization)


    #----------------------------------------------------------------------
    def restore_default(self):

        self.checkBox_mips16.select()
        self.comboBox_heapsize.set(self.HEAPSIZE.keys()[1])
        self.comboBox_optimization.set(self.OPTIMIZATION[1])


    #----------------------------------------------------------------------
    def accept_config(self):

        self.save_config()
        self.main.configIDE.save_config()
        self.quit()


    #----------------------------------------------------------------------
    def save_config(self):

        self.main.configIDE.set("Board", "mips16", self.mips16_var.get()==1)
        heapsize = self.HEAPSIZE[self.comboBox_heapsize.get()]
        self.main.configIDE.set("Board", "heapsize", heapsize)
        self.main.configIDE.set("Board", "optimization", self.comboBox_optimization.get())
コード例 #32
0
ファイル: gui.py プロジェクト: sneakypete81/pylint-patcher
    def init_gui(self):
        """init helper"""
        #setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        # Binding F5 application-wide to run lint
        self.root.bind('<F5>', self.run_lint)

        #Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lbMessages = Listbox(msg_frame,
                                  yscrollcommand=rightscrollbar.set,
                                  xscrollcommand=bottomscrollbar.set,
                                  bg="white")
        self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile)
        self.lbMessages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lbMessages.yview)
        bottomscrollbar.config(command=self.lbMessages.xview)

        #Message context menu
        self.mnMessages = Menu(self.lbMessages, tearoff=0)
        self.mnMessages.add_command(label="View in sourcefile",
                                    command=self.show_sourcefile)
        self.mnMessages.add_command(label="Add to ignore patchfile",
                                    command=self.add_to_ignore_patchfile)
        self.lbMessages.bind("<Button-3>", self.show_messages_context)

        #History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(history_frame,
                                   yscrollcommand=rightscrollbar2.set,
                                   xscrollcommand=bottomscrollbar2.set,
                                   bg="white")
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind('<Double-Button-1>', self.select_recent_file)
        self.set_history_window()

        #status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        #labels
        self.lblRatingLabel = Label(rating_frame, text='Rating:')
        self.lblRatingLabel.pack(side=LEFT)
        self.lblRating = Label(rating_frame, textvariable=self.rating)
        self.lblRating.pack(side=LEFT)
        Label(mid_frame, text='Recently Used:').pack(side=LEFT)
        Label(top_frame, text='Module or package').pack(side=LEFT)

        #file textbox
        self.txtModule = Entry(top_frame, background='white')
        self.txtModule.bind('<Return>', self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)

        #results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(res_frame,
                               yscrollcommand=rightscrollbar.set,
                               xscrollcommand=bottomscrollbar.set,
                               bg="white",
                               font="Courier")
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        #buttons
        Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
        Button(top_frame,
               text='Open Package',
               command=(lambda: self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)

        #radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(check_frame,
                        text="Information",
                        fg=COLORS['(I)'],
                        variable=self.information_box,
                        command=self.refresh_msg_window)
        c = Checkbutton(check_frame,
                        text="Convention",
                        fg=COLORS['(C)'],
                        variable=self.convention_box,
                        command=self.refresh_msg_window)
        r = Checkbutton(check_frame,
                        text="Refactor",
                        fg=COLORS['(R)'],
                        variable=self.refactor_box,
                        command=self.refresh_msg_window)
        w = Checkbutton(check_frame,
                        text="Warning",
                        fg=COLORS['(W)'],
                        variable=self.warning_box,
                        command=self.refresh_msg_window)
        e = Checkbutton(check_frame,
                        text="Error",
                        fg=COLORS['(E)'],
                        variable=self.error_box,
                        command=self.refresh_msg_window)
        f = Checkbutton(check_frame,
                        text="Fatal",
                        fg=COLORS['(F)'],
                        variable=self.fatal_box,
                        command=self.refresh_msg_window)
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        #check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(radio_frame,
                             text="Report",
                             variable=self.box,
                             value="Report",
                             command=self.refresh_results_window)
        rawMet = Radiobutton(radio_frame,
                             text="Raw metrics",
                             variable=self.box,
                             value="Raw metrics",
                             command=self.refresh_results_window)
        dup = Radiobutton(radio_frame,
                          text="Duplication",
                          variable=self.box,
                          value="Duplication",
                          command=self.refresh_results_window)
        ext = Radiobutton(radio_frame,
                          text="External dependencies",
                          variable=self.box,
                          value="External dependencies",
                          command=self.refresh_results_window)
        stat = Radiobutton(radio_frame,
                           text="Statistics by type",
                           variable=self.box,
                           value="Statistics by type",
                           command=self.refresh_results_window)
        msgCat = Radiobutton(radio_frame,
                             text="Messages by category",
                             variable=self.box,
                             value="Messages by category",
                             command=self.refresh_results_window)
        msg = Radiobutton(radio_frame,
                          text="Messages",
                          variable=self.box,
                          value="Messages",
                          command=self.refresh_results_window)
        sourceFile = Radiobutton(radio_frame,
                                 text="Source File",
                                 variable=self.box,
                                 value="Source File",
                                 command=self.refresh_results_window)
        report.select()
        report.grid(column=0, row=0, sticky=W)
        rawMet.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=W)
        stat.grid(column=0, row=1, sticky=W)
        msgCat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, sticky=W)
        sourceFile.grid(column=3, row=1, sticky=W)

        #dictionary for check boxes and associated error term
        self.msg_type_dict = {
            'I': lambda: self.information_box.get() == 1,
            'C': lambda: self.convention_box.get() == 1,
            'R': lambda: self.refactor_box.get() == 1,
            'E': lambda: self.error_box.get() == 1,
            'W': lambda: self.warning_box.get() == 1,
            'F': lambda: self.fatal_box.get() == 1
        }
        self.txtModule.focus_set()
コード例 #33
0
    def initUI(self):

        self.parent.title("FIND SPE VALUE")
        self.pack(fill=BOTH, expand=True)

        self.columnconfigure(0, weight=1)
        #self.rowconfigure(0, weight=1)
        # weight attibute is used to make them growable

        self.graph_cb = BooleanVar()
        self.bins = IntVar()
        self.path = StringVar()
        self.n_files = IntVar()
        self.start_s = IntVar()
        self.end_s = IntVar()
        self.guess = IntVar()

        search = Image.open("next_logo.jpg")
        search_temp = search.resize((160, 200), Image.ANTIALIAS)
        search_aux = ImageTk.PhotoImage(search_temp)
        label1 = Label(self, image=search_aux)
        label1.image = search_aux
        label1.grid(row=0,
                    column=0,
                    columnspan=10,
                    rowspan=10,
                    sticky=E + W + S + N)

        #Number of Files and Bins. Spin Box
        self.n_files.set("2000")
        sb1 = Spinbox(self,
                      from_=1,
                      to=10000,
                      width=6,
                      textvariable=self.n_files)
        sb1.grid(row=1, column=4, sticky=W)
        sb1_label = Label(self, text="Files")
        sb1_label.grid(row=1, column=3, padx=5, sticky=E)

        self.bins.set("50")
        sb2 = Spinbox(self, from_=10, to=200, width=6, textvariable=self.bins)
        sb2.grid(row=1, column=6, sticky=W)
        sb2_label = Label(self, text="Hist. Bins")
        sb2_label.grid(row=1, column=5, padx=5, sticky=E)

        # INTEGRATION LIMITS
        Integration_label = Label(self,
                                  text="INTEGRATION",
                                  font="Verdana 12 bold")
        Integration_label.grid(row=3, column=4, padx=5, columnspan=2)
        self.start_s.set("1732")
        sb3 = Spinbox(self,
                      from_=1,
                      to=10000,
                      width=6,
                      textvariable=self.start_s)
        sb3.grid(row=4, column=4, sticky=W)
        sb3_label = Label(self, text="StartPoint")
        sb3_label.grid(row=4, column=3, padx=5, sticky=E)

        self.end_s.set("1752")
        sb4 = Spinbox(self,
                      from_=1,
                      to=10000,
                      width=6,
                      textvariable=self.end_s)
        sb4.grid(row=4, column=6, sticky=W)
        sb4_label = Label(self, text="EndPoint")
        sb4_label.grid(row=4, column=5, padx=5, sticky=E)
        sb4_label = Label(self, text="")
        sb4_label.grid(row=4, column=7, padx=5, sticky=E)

        # FITTING PARAMETERS
        Integration_label = Label(self, text="FITTING", font="Verdana 12 bold")
        Integration_label.grid(row=6, column=4, padx=5, columnspan=2)
        self.guess.set("-20")
        sb5 = Spinbox(self, from_=-50, to=-1, width=6, textvariable=self.guess)
        sb5.grid(row=7, column=4, sticky=W)
        sb5_label = Label(self, text="SPE guess")
        sb5_label.grid(row=7, column=5, padx=5, sticky=W)

        #Check buttons
        cb1 = Checkbutton(self,
                          text="MultiGraph Output",
                          variable=self.graph_cb)
        cb1.select()
        cb1.grid(row=7, column=6, sticky=W)

        #Text Box
        #self.path.set("F:/DATOS_DAC/spe_1230/2046/pmt_0_trace_evt_")
        self.path.set("spe_1230_2046.h5.z")
        e1 = Entry(self, textvariable=self.path, width=45)
        e1.grid(row=10, column=3, sticky=W, columnspan=10, padx=10, pady=5)
        e1_label = Label(self, text="DataSet path (including name file)")
        e1_label.grid(row=9, column=3, sticky=W, columnspan=10, padx=10)

        # Main buttons
        obtn = Button(self, text="GO!!", command=self.SPE_f)
        obtn.grid(row=14, column=5, sticky=E, pady=5)

        cbtn = Button(self, text="Quit", command=self.quit)
        cbtn.grid(row=14, column=6, sticky=E, pady=5)

        hbtn = Button(self, text="Help")
        hbtn.grid(row=14, column=0, sticky=W, pady=5)