Example #1
0
    def new_label(self):
        # Creating a new row header
        
        self._number_of_labels += 1

        frame_button = Frame(self._frame_of_row_numbers, height=self._row_height)
        frame_button.pack()
        frame_button.pack_propagate(False)
        
        row_label = Label(frame_button, text =self._number_of_labels, **self._labelrow_kwargs)
        row_label.bind("<1>", lambda event, index=self._number_of_labels-1: self._on_click_label(index))
        
        if self._hover_background:
            row_label.bind("<Enter>", lambda event, row_label=row_label: row_label.configure(background=self._hover_background))
            row_label.bind("<Leave>", lambda event, row_label=row_label: row_label.configure(background=self.cget("background")))

        row_label.pack(expand=True, fill=BOTH)
        
        width_of_row_numbers= max(row_label.winfo_reqwidth(), self._row_minwidth)
        
        if width_of_row_numbers > self._width_of_row_numbers:
            self._width_of_row_numbers = width_of_row_numbers
            
            for slave in self._frame_of_row_numbers.pack_slaves():
                slave.configure(width=width_of_row_numbers)
        else:
            frame_button.configure(width=width_of_row_numbers)

        frame_button.update_idletasks()

        self.config(width=self._frame_of_row_numbers.winfo_reqwidth())
        self.config(scrollregion=(0, 0, self._frame_of_row_numbers.winfo_reqwidth(), self._number_of_labels*self._row_height))
Example #2
0
    def new_label(self):
        # Creating a new row header
        
        self._number_of_labels += 1

        frame_button = Frame(self._frame_of_row_numbers, height=self._row_height)
        frame_button.pack()
        frame_button.pack_propagate(False)
        
        row_label = Label(frame_button, text =self._number_of_labels, **self._labelrow_kwargs)
        row_label.bind("<1>", lambda event, index=self._number_of_labels-1: self._on_click_label(index))
        
        if self._hover_background:
            row_label.bind("<Enter>", lambda event, row_label=row_label: row_label.configure(background=self._hover_background))
            row_label.bind("<Leave>", lambda event, row_label=row_label: row_label.configure(background=self.cget("background")))

        row_label.pack(expand=True, fill=BOTH)
        
        width_of_row_numbers= max(row_label.winfo_reqwidth(), self._row_minwidth)
        
        if width_of_row_numbers > self._width_of_row_numbers:
            self._width_of_row_numbers = width_of_row_numbers
            
            for slave in self._frame_of_row_numbers.pack_slaves():
                slave.configure(width=width_of_row_numbers)
        else:
            frame_button.configure(width=width_of_row_numbers)

        frame_button.update_idletasks()

        self.config(width=self._frame_of_row_numbers.winfo_reqwidth())
        self.config(scrollregion=(0, 0, self._frame_of_row_numbers.winfo_reqwidth(), self._number_of_labels*self._row_height))
class classifier(Tk):
	def __init__(self, parent):
		Tk.__init__(self, parent)
		self.parent = parent
		self.initialise()

	def initialise(self):
		self.grid()
		self.bind('<Key>', self.key)
		with open('image_list.txt') as f:
			self.file_list = f.readlines()

		self.label = Label(self, image=self.get_image(), width=100, height=100)
		self.label.pack()

	def get_image(self):
		image_name = self.file_list.pop(0).strip()
		self.filename = image_name
		self.image = PhotoImage(file=image_name)
		return self.image

	def key(self, event):
		key = event.char
		if ord(key) >= ord('A') and ord(key) <= ord('z') or key == ' ':
			print "Recognised as ", key
			self.label.configure(image=self.get_image())
			with open('lists/'+key+'.txt', 'a') as f:
				f.write(self.filename+"\n")
class classifier(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent
        self.initialise()

    def initialise(self):
        self.grid()
        self.bind('<Key>', self.key)
        with open('image_list.txt') as f:
            self.file_list = f.readlines()

        self.label = Label(self, image=self.get_image(), width=100, height=100)
        self.label.pack()

    def get_image(self):
        image_name = self.file_list.pop(0).strip()
        self.filename = image_name
        self.image = PhotoImage(file=image_name)
        return self.image

    def key(self, event):
        key = event.char
        if ord(key) >= ord('A') and ord(key) <= ord('z') or key == ' ':
            print "Recognised as ", key
            self.label.configure(image=self.get_image())
            with open('lists/' + key + '.txt', 'a') as f:
                f.write(self.filename + "\n")
class App:

    def __init__(self, root):
        self.root = root
        self.img = self.readImage('/home/juan/Desktop/[email protected]')
        frame = Frame(root, width=100, height=100)

        # Put it in the display window
        self.label = Label(frame, image=self.img)
        self.label.pack()

        button = Button(frame, command=self.changeImage, text='OK')
        button.pack()

        frame.pack()

    def changeImage(self):
        self.img = self.readImage('/home/juan/Desktop/Bill_Clinton_0002.jpg')
        self.label.configure(image=self.img)
        self.label.pack()
        self.root.update_idletasks()

    def readImage(self, path):
        img = cv2.imread(path)

        # Rearrang the color channel
        b, g, r = cv2.split(img)
        img = cv2.merge((r, g, b))

        # Convert the Image object into a TkPhoto object
        im = Image.fromarray(img)
        return ImageTk.PhotoImage(image=im)
Example #6
0
class ImageFrame(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.setup()
        self.initUI()
        self.schedule()

    def setup(self):
        self.capture = cv2.VideoCapture(0)
        self.key = StringVar()
        self.val = DoubleVar()


    def initUI(self):
        self.parent.title("Buttons")
        self.style = Style()
        self.style.theme_use("default")

        frame = Frame(self, relief=GROOVE, borderwidth=5)
        frame.pack(fill=BOTH, expand=1)
        self.pack(fill = BOTH, expand = 1)

        self.imageLabel = Label(frame, image = "")
        self.imageLabel.pack(fill=BOTH, expand=1)

        closeButton = Button(self, text="Close")
        closeButton.pack(side=RIGHT)
        okButton = Button(self, text="OK")
        okButton.pack(side=RIGHT)

        options = [item for item in dir(cv2.cv) if item.startswith("CV_CAP_PROP")]
        option = OptionMenu(self, self.key, *options)
        self.key.set(options[0])
        option.pack(side="left")

        spin = Spinbox(self, from_=0, to=1, increment=0.05)
        self.val = spin.get()
        spin.pack(side="left")


    def schedule(self):
        def captureImg():
            ret, frame = self.capture.read()
            # Convert the Image object into a TkPhoto object
            b,g,r = cv2.split(frame)
            frame = cv2.merge((r,g,b))
            im = Image.fromarray(frame)
            im = im.resize((640, 480),Image.ANTIALIAS)


            imgtk = ImageTk.PhotoImage(image=im)
            # Put it in the display window
            self.imageLabel.configure(image = imgtk)
            self.imageLabel.image = imgtk
            self.after(100, captureImg)

        self.after(100, captureImg)
Example #7
0
    def runSim(self):
        import Tkinter
        from Tkinter import Tk, Button, Frame, Label
        root = Tk()
        root.title('lights simulator')

        def onNext():
            self.nextProgram()
            pgmName.configure(text=str(self.currentProgramIndex) + ') ' +
                              self.getProgramName())
            #print self.getProgramName()

        def onPrev():
            self.prevProgram()
            pgmName.configure(text=str(self.currentProgramIndex) + ') ' +
                              self.getProgramName())
            #print self.getProgramName()

        pgmFrame = Frame(root)
        nxt = Button(pgmFrame, text="next", command=onNext)
        nxt.pack(side=Tkinter.LEFT)
        prev = Button(pgmFrame, text="prev", command=onPrev)
        prev.pack(side=Tkinter.LEFT)
        pgmName = Label(pgmFrame, text=self.getProgramName())
        pgmName.configure(text=str(self.currentProgramIndex) + ') ' +
                              self.getProgramName())
        pgmName.pack(side=Tkinter.LEFT, fill=Tkinter.X)
        pgmFrame.pack(fill=Tkinter.X)

        lightDarkFrame = Frame(root)
        front = Button(lightDarkFrame, text="front", command=lambda: self.frontBtn())
        front.pack(side=Tkinter.LEFT)
        dark = Button(lightDarkFrame, text="dark", command=lambda: self.darkBtn())
        dark.pack(side=Tkinter.LEFT)
        lightDarkFrame.pack()

        btnFrame = Frame(root)
        for i in range(5):
            b = Button(btnFrame, text=str(i), command=lambda n=i: self.btn(n))
            b.pack(side=Tkinter.LEFT)
        btnFrame.pack()

        lightFrame = Frame(root, height=400, width=400)
        lightFrame.pack()
        for name, l in allLights.items():
            w = Label(lightFrame, text="  ", bg="black")
            l['light'].setSimWidget(w)
            w.place(x=l['simX'], y=350-l['simY'])

        def update():
            for name, l in allLights.items():
                l['light'].update()
            root.after(10, update)
        update()
        root.mainloop()
Example #8
0
class TrackingGotoCoordsDialog(Dialog):
    def __init__(self,
                 parent              = None,
                 ):
        #set up dialog windows
        Dialog.__init__(self,
                        parent = parent,
                        title = "Tracking Go to Coords", 
                        buttons = ('OK',),
                        defaultbutton = 'OK',
                       )
        main_frame = self.interior()
        az_frame = Frame(main_frame)
        self.az_field = EntryField(az_frame,
                                   labelpos    = 'w',
                                   label_text  = "  azimuth target:",
                                   label_font  = FIELD_LABEL_FONT,
                                   entry_width = FIELD_ENTRY_WIDTH,
                                   #entry_state = 'readonly',
                                   )
        self.az_field.pack(side='left', anchor="w", expand='no')
        self.az_limits_label = Label(az_frame, text = "(min=???,max=???)")
        self.az_limits_label.pack(side='right', anchor='w', expand='no')
        az_frame.pack(side='top')
        el_frame = Frame(main_frame)
        self.el_field = EntryField(el_frame,
                                   labelpos    = 'w',
                                   label_text  = "elevation target:",
                                   label_font  = FIELD_LABEL_FONT,
                                   entry_width = FIELD_ENTRY_WIDTH,
                                   #entry_state = 'readonly',
                                   )
        self.el_field.pack(side='left', anchor="w", expand='no')
        self.el_limits_label = Label(el_frame, text = "(min=???,max=???)")
        self.el_limits_label.pack(side='right', anchor='w', expand='no')
        el_frame.pack(side='top')
        
    def set_limits(self, az_CW_limit, az_CCW_limit, el_CW_limit, el_CCW_limit):
        az_min = min(az_CW_limit, az_CCW_limit)
        az_max = max(az_CW_limit, az_CCW_limit)
        self.az_field.configure( validate = Validator(_min=az_min,_max=az_max,converter=float))
        self.az_limits_label.configure(text="(min=%0.2f,max=%0.2f)" % (az_min,az_max))
        el_min = min(el_CW_limit, el_CCW_limit)
        el_max = max(el_CW_limit, el_CCW_limit)
        self.el_field.configure(validate = Validator(_min=el_min,_max=el_max,converter=float))
        self.el_limits_label.configure(text="(min=%0.2f,max=%0.2f)" % (el_min,el_max))
      
    def activate(self):
        "override activate to construct and send back the action and the new values"
        action = Dialog.activate(self)
        if action == 'OK' and not (self.az_field.valid() and self.el_field.valid()):
            return self.activate()
        return action
Example #9
0
class image():
    def __init__(self, frm):
        self.frm = frm.frame
        self.widget = Label(self.frm, image=None)

    def set_image(self, path):
        self.bard = Image.open(path)
        self.bard = self.bard.resize((500, 500))
        ba = ImageTk.PhotoImage(self.bard)
        self.widget.configure(image=ba)
        self.widget.image = self.ba
        self.widget.pack()
class image:
    def __init__(self, frm):
        self.frm = frm.frame
        self.widget = Label(self.frm, image=None)

    def set_image(self, path):
        self.bard = Image.open(path)
        self.bard = self.bard.resize((500, 500))
        ba = ImageTk.PhotoImage(self.bard)
        self.widget.configure(image=ba)
        self.widget.image = self.ba
        self.widget.pack()
class JoystickFrame(LabelFrame):
    def __init__(self, master, tracker, text="Joystick", **options):
        LabelFrame.__init__(self, master, text=text, **options)
        self.tracker = tracker

        self.width = 400
        self.height = 400
        self.canvas = Canvas(self, height=self.height, width=self.width)
        self.canvas.grid()
        self.canvas.create_oval((self.width/2 - 3, self.height/2 - 3,
                                 self.width/2 + 3, self.height/2 + 3))
        self.canvas.bind("<Button-1>",
                         bg_caller(lambda event: self.move_tracker(event)))
        self.canvas.bind("<Motion>", self.update_label)

        self.motion_label = Label(self, text="",
                                  font=tkFont.Font(family="Courier"))
        self.motion_label.grid()

        f = LabelFrame(self, text="Sensitivity")
        self.sensitivity_scale = Scale(f, from_=0, to=10,
                                       resolution=0.01,
                                       orient=HORIZONTAL,
                                       length=self.width)
        self.sensitivity_scale.set(5)
        self.sensitivity_scale.grid()
        f.grid()

    @property
    def sensitivity(self):
        return self.sensitivity_scale.get() / 2000.

    def get_delta(self, event):
        dx = event.x - int(self.canvas['width'])/2.
        dy = event.y - int(self.canvas['height'])/2.
        dx_rad = dx*self.sensitivity
        dy_rad = dy*self.sensitivity
        dtheta = dy_rad
        dphi = -dx_rad
        return (dtheta, dphi)

    def update_label(self, event):
        dtheta, dphi = self.get_delta(event)
        self.motion_label.configure(text="<{:8.5f}, {:8.5f}>".format(dtheta,
                                                                     dphi))

    def move_tracker(self, event):
        dtheta, dphi = self.get_delta(event)
        self.tracker.move(0, dtheta, dphi)
        logger.info("Moved tracker by ({}, {})".format(dtheta, dphi))
Example #12
0
class DemoWindow(Tk):
    """
    Class to manage the window of the demo
    """
    def __init__(self, fileinput):
        """
        Build the visual interface with images and fields to the images data
        """
        fileinput = realpath(fileinput)
        self.imgs = ImageManager(fileinput)
        Tk.__init__(self)
        self.title("Frame sequence")
        # width x height + x_offset + y_offset:
        self.geometry(str(self.imgs.width+20)+"x"+str(self.imgs.height+30)+"+1+1")
        self.i = 0
        self.prev = 0

        self.frame = Label(self, text="")
        self.frame.grid(row=0, column=1, padx=10, pady=2, sticky=N+S+W)

        self.image = Label(self, image=None)
        self.image.grid(row=1, column=1, padx=10, pady=2, sticky=N+S+W)

        self.update_window()


    def updateImage(self, img):
        """
        Update the Label containing the image
        """
        self.tkimage = ImageTk.PhotoImage(img)
        self.image.configure(image=self.tkimage)


    def updateLabelFrame(self, text):
        """
        Update the label containing the number of the frame
        """
        self.frame.configure(text='Frame: '+text)


    def update_window(self):
        """
        Update the window and its elements every second
        """
        name, fimg = self.imgs.nextImage()
        self.updateImage(fimg)
        self.updateLabelFrame(name)
        self.after(1, self.update_window)
class TasksGui(object):
    """A small Tkinter GUI that shows the tasks"""
    def __init__(self):
        self.root = Tk()
        self.size = (self.root.winfo_screenwidth(),
                     self.root.winfo_screenheight())
        self.root.overrideredirect(1)
        self.root.geometry("%dx%d+0+0" % self.size)
        self.image_count = 19
        self.task_index = 0
        self.task_images = range(self.image_count)
        self.photo_images = range(self.image_count)
        for i in range(self.image_count):
            self.task_images[i] = Image.open("img/" + str(i + 1) + ".png")
            self.task_images[i] = self.task_images[i].resize(
                self.size, Image.ANTIALIAS)
            self.photo_images[i] = ImageTk.PhotoImage(self.task_images[i])
            print "Preload img/" + str(i + 1) + ".png"
        self.panel = Label(self.root,
                           image=self.photo_images[0],
                           background='white')
        self.panel.pack(side=TOP, fill=BOTH, expand=YES)
        self.root.update()

    def next_task(self):
        """Continues with the next task"""
        self.task_index = self.task_index + 1
        self.panel.configure(image=self.photo_images[self.task_index])
        self.panel.image = self.photo_images[self.task_index]
        self.root.update()

    def is_finished(self):
        """Returns the status of the tasks"""
        if self.task_index >= self.image_count - 1:
            return True
        return False

    def get_task_index(self):
        """Returns the task index"""
        return self.task_index

    def quit(self):
        """Qit the GUI"""
        self.root.quit()
        self.root.update()
Example #14
0
    def cycle_through_images(self, images, label):

        image = images.next()

        size = self.parsegeometry(self.window.geometry())  # Grab screen size
        window_size = size[0], size[1]

        image.thumbnail(window_size, Image.ANTIALIAS)  # Resize to fit screen
        tkimage = ImageTk.PhotoImage(image)

        if not label:
            label = Label(self.window, image=tkimage)

        label.pack(fill=BOTH, expand=YES)
        label.configure(image=tkimage)
        label.image = tkimage

        self.window.after(10000, self.cycle_through_images, images, label)
Example #15
0
    class TkDemoWindow(TkSlidingWindow):

        def __init__(self, parent):
            from Tkinter import Tk, Label, Button
            self.parent = parent
            self.win = Tk(className='moving')
            self.win.overrideredirect(1)
            self.win.tkraise()
            self.label = Label(self.win, text=' '*25, font='fixed')
            self.label.pack(padx=20, pady=10)
            self.button = Button(self.win, text='OK', command=self.parent.hide)
            self.button.pack(pady=5)
            tksupport.install(self.win)

        def demoText(self, text):
            self.label.configure(text=text)
            self.win.geometry('+%d+%d'%self.getScreenSize())
            self.label.pack()
class _Label(Frame):
    def __init__(self, master=None, width=0, height=0, **kwargs):
        self.width = width
        self.height = height

        Frame.__init__(self, master, width=self.width, height=self.height)
        self.label = Label(self, **kwargs)
        self.label.pack(expand=True, fill='both')
        self.label.saved_image = None

    def pack(self, *args, **kwargs):
        Frame.pack(self, *args, **kwargs)
        self.pack_propagate(False)

    def grid(self, *args, **kwargs):
        Frame.grid(self, *args, **kwargs)
        self.grid_propagate(False)

    @property
    def image(self):
        return self.label.saved_image

    def set_img(self, img):
        # img = Image.open(filename)
        width = self.width if img.width > self.width else img.width
        height = self.height if img.height > self.height else img.height

        if width == self.width or height == self.height:
            print 'resized'
            self_ratio = 1.0 * self.width / self.height
            img_ratio = 1.0 * img.width / img.height

            height = self.height if self_ratio > img_ratio else img.height
            width = self.height * img_ratio

            resized = img.resize((int(width), int(height)), Image.ANTIALIAS)
        else:
            resized = img

        resized = PhotoImage(resized)
        self.label.configure(image=resized)
        self.label.image = resized
        self.label.saved_image = img
Example #17
0
 def showtip(self, text):
     self.text = text
     if self.tipwindow or not self.text:
         return
     x, y, cx, cy = self.widget.bbox('insert')
     x = x + self.widget.winfo_rootx() + 60
     y = y + cy + self.widget.winfo_rooty() + 30
     self.tipwindow = tw = Toplevel(self.widget)
     tw.wm_overrideredirect(1)
     tw.wm_geometry('+%d+%d' % (x, y))
     label = Label(tw, text=self.text)
     label.configure(justify=LEFT)
     label.configure(relief=SOLID, bd=1)
     label.configure(bg=GrayScale(60),
                     fg=GrayScale(220),
                     font=MyFonts['Default'])
     label.pack(ipadx=1)
Example #18
0
class Viewer():

    def __init__(self, image):
        self.original = image
        self.image = image.copy()
        self.window = Tk()

        self.genViews()
        self.currentView = StringVar(self.window)
        self.currentView.set('Original')
        options = self.filters.keys();options.sort()
        self.views = OptionMenu(self.window, self.currentView,
                *options, command=self.applyFilter)
        self.views.pack()

        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage = Label(image=self.tkImage)
        self.lblImage.bind('<Button-1>', self.displayInfos)
        self.lblImage.bind('<Button-3>', self.save)
        self.lblImage.image = self.tkImage
        self.lblImage.pack()

        self.status = StringVar()
        self.lblStatus = Label(textvariable=self.status, justify='right')
        self.lblStatus.pack()

        self.window.mainloop()

    def displayInfos(self, event):
        """
        Displays the coordinates in the status bar
        """
        x = int((event.x-0.1)/args.scalefactor)
        y = int((event.y-0.1)/args.scalefactor)
        pixel = orig.getpixel((x, y))
        self.setStatus("Coordinates : (%s:%s) - Pixel value : %s" %
                (x, y, str(pixel)))

    def setStatus(self, text):
        """
        Changes the text in the status bar
        """
        self.status.set(text)

    def save(self, event):
        """
        Saves the filtered image to a file
        """
        options = {'filetypes':[('PNG','.png'),('GIF','.gif')]}
        outfile = tkFileDialog.asksaveasfilename(**options)
        if outfile == '':
            return
        else:
            self.image.save(outfile)
            return

    def genViews(self):
        """
        Generates filters based on the source image
        """
        self.filters = {}
        for plug in viewPlugins:
            self.filters.update({plug.name:viewPlugins.index(plug)})

    def applyFilter(self, view):
        """
        Applies a filter to the image
        """
        view = self.filters[self.currentView.get()]
        plugin = viewPlugins[view]
        if plugin.parameters:
            for param in plugin.parameters.keys():
                a = tkSimpleDialog.askinteger(
                        'Question', plugin.parameters[param])
                if a is not None:
                    setattr(viewPlugins[view], param, a)
        self.image = viewPlugins[view].process(self.original)

        self.showImage(self.currentView.get(), self.image)
        self.setStatus("")
        return

    def showImage(self, title, image):
        """
        Updates the image in the window
        """
        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage.configure(image=self.tkImage)
        self.lblImage.image = self.tkImage
Example #19
0
class Gui:
    def __init__(self, master, head_title):
        self.master = master
        self.head_title = head_title
        master.title(head_title)

        # params definition
        self.n_clusters = 4
        self.n_init = 10
        self.file_path = 'C:/'
        self.is_pre_processed = False
        self.processor = None
        self.cluster = None

        # Tkinter gui

        self.file_path_text = StringVar(value=self.file_path)
        self.file_path_label = Label(master, text='Data path:')
        self.file_path_entry = Entry(master, textvariable=self.file_path_text, width=50)
        self.browse_button = Button(master, text='Browse', command=self.browse)

        self.n_clusters_text = StringVar(value=self.n_clusters)
        self.n_clusters_label = Label(master, text='Num of clusters k:')
        self.n_clusters_entry = Entry(master, textvariable=self.n_clusters_text)

        self.n_init_text = StringVar(value=self.n_init)
        self.n_init_label = Label(master, text='Num of runs:')
        self.n_init_entry = Entry(master, textvariable=self.n_init_text)

        self.pre_process_button = Button(master, text='Pre-process', command=self.pre_process)
        self.build_model_button = Button(master, text='Cluster', command=self.build_model)

        self.scatter_label = Label(self.master)
        self.horopleth_label = Label(master)
        # LAYOUT

        self.file_path_label.grid(row=0, column=0, sticky=W)
        self.file_path_entry.grid(row=0, column=1, columnspan=2)
        self.browse_button.grid(row=0, column=2, sticky=E)

        self.n_clusters_label.grid(row=1, column=0, sticky=W)
        self.n_clusters_entry.grid(row=1, column=1, columnspan=2, sticky=W+E)

        self.n_init_label.grid(row=2, column=0, sticky=W)
        self.n_init_entry.grid(row=2, column=1, columnspan=2, sticky=W+E)

        self.pre_process_button.grid(row=3, column=1, sticky=W)
        self.build_model_button.grid(row=4, column=1, sticky=W)

        self.scatter_label.grid(row=5, column=0, sticky=W)
        self.horopleth_label.grid(row=5, column=1, sticky=E)

    def browse(self):
        # browse method for choosing the data file
        path = tkFileDialog.askopenfilename()
        if path is None or path == '':
            return

        self.file_path = path
        self.file_path_text.set(self.file_path)

    def pre_process(self):
        # pre process the data to fit into the algorithm
        if self.processor is not None:
            # if we already ran this, ask the user if he wants to run it again
            result = tkMessageBox.askquestion(
                message="pre-processing has already been made.\nare you sure you want to run it again?'",
                icon='warning', title=self.head_title)
            if result != 'yes':
                return
        self.processor = None
        self.is_pre_processed = False
        try:
            # verify the file can be pre-processed
            self.file_path = self.file_path_text.get()
            processor = PreProcess(self.file_path)
            if processor.verifications() is False:
                tkMessageBox.showerror(title=self.head_title, message=processor.error_message)
                return

            # process the data
            processor.pre_process()
            tkMessageBox.showinfo(title=self.head_title, message='Preprocessing completed successfully')
            self.processor = processor
            self.is_pre_processed = True
        except Exception as err:
            template = "An exception of type {0} occurred. Arguments:{1}"
            message = template.format(type(err).__name__, err)
            print_exc(err, file=stdout)
            tkMessageBox.showerror(title=self.head_title, message=message)

    def build_model(self):
        # build the kmeans model
        if not self.is_pre_processed:
            tkMessageBox.showerror(title=self.head_title, message="pre processing is not validated yet")
            return

        if self.cluster is not None:
            # if we already ran the clustering, verify if we really want to run it again
            result = tkMessageBox.askquestion(
                message="clustering has already been made.\nare you sure you want to run it again?",
                icon='warning', title=self.head_title)
            if result != 'yes':
                return
        self.cluster = None
        try:
            # create the kmeans model
            self.n_clusters = self.n_clusters_text.get()
            self.n_init = self.n_init_text.get()
            model = BuildCluster(self.n_clusters, self.n_init, self.processor.df)
            if model.verifications() is False:
                tkMessageBox.showerror(title=self.head_title, message=model.error_message)
                return

            model.build_cluster()
            self.cluster = model
            # draw the graphs in the gui
            self.draw_graphs()
            tkMessageBox.showinfo(title=self.head_title, message='Clustering Finished successfully!')
        except Exception as err:
            template = "An exception of type {0} occurred. Arguments:{1}"
            message = template.format(type(err).__name__, err)
            print_exc(err, file=stdout)
            tkMessageBox.showerror(title=self.head_title, message=message)

    def draw_graphs(self):
        # draw scatter graph using matPlotLib and plotly
        self.draw_scatter()
        self.draw_horopleth()

    def draw_scatter(self):
        # Draw a scatter plot of Generosity vs social support
        df = self.cluster.df
        fig_path = 'scatter.png'
        plt.scatter(x=df['Generosity'], y=df['Social support'], c=df['cluster'], alpha=0.5)
        plt.xlabel('Generosity')
        plt.ylabel('Social support')
        plt.title("Scatter of Generosity vs Social Support, colored by clusters")
        plt.savefig(fig_path)
        # convert from png to gif
        convert_png_to_gif(fig_path)
        # display in GUI
        photo = PhotoImage(file=fig_path.replace('png', 'gif'))
        self.scatter_label.configure(image=photo, width='400px', height='400px')
        self.scatter_label.image = photo

    def draw_horopleth(self):
        # Draw a horopleth of the country clusters
        df = self.cluster.df
        py.sign_in('omrikipiki', 'VcDvTak2bEIiyOfiaxMj')
        data = [dict(
            type='choropleth',
            locations=df['country'],
            z=df['cluster'],
            text=df['country'],
            locationmode='country names',
            colorscale=[[0, "rgb(5, 10, 172)"], [0.35, "rgb(40, 60, 190)"], [0.5, "rgb(70, 100, 245)"],
                        [0.6, "rgb(90, 120, 245)"], [0.7, "rgb(106, 137, 247)"], [1, "rgb(220, 220, 220)"]],
            autocolorscale=False,
            reversescale=True,
            marker=dict(
                line=dict(
                    color='rgb(180,180,180)',
                    width=0.5
                )),
            colorbar=dict(
                # autotick=False,
                title='Cluster Group'),
        )]

        layout = dict(
            title='K-Means Clustering Visualization',
            geo=dict(
                showframe=False,
                showcoastlines=False,
                projection=dict(
                    type='Mercator'
                )
            )
        )
        fig = dict(data=data, layout=layout)

        py.iplot(fig, validate=False, filename='d3-world-map')

        fig_path = 'choromap.png'
        py.image.save_as(fig, filename=fig_path)
        # convert to gif
        convert_png_to_gif(fig_path)
        # put in GUI
        photo = PhotoImage(file=fig_path.replace('png', 'gif'))
        self.horopleth_label.configure(image=photo, width='600px', height='600px')
        self.horopleth_label.image = photo
Example #20
0
class TopLevel(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, background="gray")
        self.parent = parent
        self.init_global_vars()
        self.init_UI()
        self.detect_debug_mode()
        self.set_state_stopped()

    def init_global_vars(self):
        self.switch_status = 'none'
        self.home_result = IntVar()
        self.move_result = IntVar()
        self.timer_active = IntVar()
        self.test_active = False
        self.test_paused = False

        self.timer = [0, 0]
        self.timer_reset_val = [0, 0]

        #self.active_cycle = 0
        #self.active_temp = 'foo'
        #self.up_motor_res = 2
        #self.right_motor_res = 2

        self.move_motor_resolution = 2

        self.up_full_steps = 3200
        self.right_full_steps = 7200

        self.debug_mode = False

        self.event_schedule = []

        self.move_total_duration = 0
        self.move_direction = ''
        self.move_started_time = datetime.now()
        self.pause_time = datetime.now()
        self.resume_time = datetime.now()
        self.planned_steps = 0

    def init_UI(self):

        self.parent.title('Liquid Thermal Shock Tester v0.2')
        self.pack(fill=BOTH, expand=True)
        options_frame = Frame(self, background='gray', pady=5, padx=5)
        options_frame.pack(side=LEFT, fill=BOTH, expand=True)

        options_label = Label(options_frame,
                              text='Test Setup',
                              background='gray',
                              font=('Courier', 22, 'bold'),
                              justify=LEFT)
        ul_bold_font = Font(options_label, options_label.cget('font'))
        ul_bold_font.configure(underline=True)
        options_label.configure(font=ul_bold_font)
        options_label.pack(anchor=CENTER, side=TOP, padx=5, pady=5)

        cycles_frame = Frame(options_frame, background='gray', pady=5)
        cycles_frame.pack(side=TOP, fill=BOTH, expand=True)

        cycles_label = Label(cycles_frame,
                             text='# of cycles',
                             background='gray',
                             font=('Courier', 12),
                             justify=CENTER)
        cycles_label.grid(row=0,
                          column=0,
                          rowspan=1,
                          columnspan=2,
                          sticky='news')
        ul_plain_font = Font(cycles_label, cycles_label.cget('font'))
        ul_plain_font.configure(underline=True)
        cycles_label.configure(font=ul_plain_font)

        self.cycles_select_disp = Label(cycles_frame,
                                        text='5',
                                        background='white',
                                        font=('Courier', 32))
        self.cycles_select_disp.grid(row=1,
                                     column=0,
                                     rowspan=2,
                                     columnspan=1,
                                     sticky='wens',
                                     padx=5,
                                     pady=5)

        self.cycles_increase_button = Button(cycles_frame,
                                             text=u'\u25b2',
                                             font=('Courier', 18, 'bold'),
                                             command=self.cycles_increment)
        self.cycles_increase_button.grid(row=1,
                                         column=1,
                                         rowspan=1,
                                         columnspan=1,
                                         sticky='wens',
                                         padx=5,
                                         pady=5)

        self.cycles_decrease_button = Button(cycles_frame,
                                             text=u'\u25BC',
                                             font=('Courier', 18, 'bold'),
                                             command=self.cycles_decrement)
        self.cycles_decrease_button.grid(row=2,
                                         column=1,
                                         rowspan=1,
                                         columnspan=1,
                                         sticky='wens',
                                         padx=5,
                                         pady=5)

        self.fix_grid(cycles_frame)

        soak_time_frame = Frame(options_frame, background='gray', pady=5)
        soak_time_frame.pack(side=TOP, fill=BOTH, expand=True)

        soak_time_label = Label(soak_time_frame,
                                text='Minutes per Soak',
                                background='gray',
                                font=('Courier', 12),
                                justify=CENTER)
        soak_time_label.grid(row=0,
                             column=0,
                             rowspan=1,
                             columnspan=2,
                             sticky='news')
        soak_time_label.configure(font=ul_plain_font)

        self.soak_time_disp = Label(soak_time_frame,
                                    text='5',
                                    background='white',
                                    font=('Courier', 32))
        self.soak_time_disp.grid(row=1,
                                 column=0,
                                 rowspan=2,
                                 columnspan=1,
                                 sticky='wens',
                                 padx=5,
                                 pady=5)

        self.soak_time_increment_button = Button(
            soak_time_frame,
            text=u'\u25b2',
            font=('Courier', 18, 'bold'),
            command=self.soak_time_increment)
        self.soak_time_increment_button.grid(row=1,
                                             column=1,
                                             rowspan=1,
                                             columnspan=1,
                                             sticky='wens',
                                             padx=5,
                                             pady=5)

        self.soak_time_decrement_button = Button(
            soak_time_frame,
            text=u'\u25BC',
            font=('Courier', 18, 'bold'),
            command=self.soak_time_decrement)
        self.soak_time_decrement_button.grid(row=2,
                                             column=1,
                                             rowspan=1,
                                             columnspan=1,
                                             sticky='wens',
                                             padx=5,
                                             pady=5)

        self.fix_grid(soak_time_frame)

        controls_frame = Frame(self, background='gray')
        controls_frame.pack(side=LEFT, fill=BOTH, expand=True)

        run_pause_frame = Frame(controls_frame, background='gray')
        run_pause_frame.pack(side=TOP, fill=BOTH, expand=True, pady=5)

        self.run_button = Button(run_pause_frame,
                                 text='RUN',
                                 background='green',
                                 activebackground='green',
                                 font=('Courier', 30, 'bold'),
                                 width=5,
                                 command=self.run_init)
        self.run_button.grid(row=0, column=0, sticky='wens', padx=5, pady=5)

        self.pause_button = Button(run_pause_frame,
                                   text='PAUSE',
                                   background='orange',
                                   activebackground='orange',
                                   font=('Courier', 30, 'bold'),
                                   width=5,
                                   command=self.pause_button_pressed)
        self.pause_button.grid(row=0, column=1, sticky='wens', padx=5, pady=5)

        self.fix_grid(run_pause_frame)

        stop_button = Button(controls_frame,
                             text='STOP',
                             background='red',
                             activebackground='red',
                             font=('Courier', 36, 'bold'),
                             command=self.stop_test)
        stop_button.pack(side=TOP, fill=BOTH, expand=True, padx=5)

        jog_frame = Frame(controls_frame, background='gray')
        jog_frame.pack(side=TOP, fill=BOTH, expand=True, pady=5)

        jog_label = Label(jog_frame,
                          text='Motor\rjog',
                          font=('Courier', 12, 'bold'),
                          background='gray')
        jog_label.grid(row=1, column=1)

        self.jog_up_button = Button(jog_frame,
                                    text=u'\u25b2',
                                    font=('Courier', 18, 'bold'))
        self.jog_up_button.grid(row=0,
                                column=1,
                                rowspan=1,
                                columnspan=1,
                                sticky='wens',
                                padx=5,
                                pady=5)
        self.jog_up_button.bind("<Button-1>", self.jog_up_on)
        self.jog_up_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_left_button = Button(jog_frame,
                                      text=u'\u25C4',
                                      font=('Courier', 18, 'bold'))
        self.jog_left_button.grid(row=1,
                                  column=0,
                                  rowspan=1,
                                  columnspan=1,
                                  sticky='wens',
                                  padx=5,
                                  pady=5)
        self.jog_left_button.bind("<Button-1>", self.jog_left_on)
        self.jog_left_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_right_button = Button(jog_frame,
                                       text=u'\u25BA',
                                       font=('Courier', 18, 'bold'))
        self.jog_right_button.grid(row=1,
                                   column=2,
                                   rowspan=1,
                                   columnspan=1,
                                   sticky='wens',
                                   padx=5,
                                   pady=5)
        self.jog_right_button.bind("<Button-1>", self.jog_right_on)
        self.jog_right_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_down_button = Button(jog_frame,
                                      text=u'\u25BC',
                                      font=('Courier', 18, 'bold'))
        self.jog_down_button.grid(row=2,
                                  column=1,
                                  rowspan=1,
                                  columnspan=1,
                                  sticky='wens',
                                  padx=5,
                                  pady=5)
        self.jog_down_button.bind("<Button-1>", self.jog_down_on)
        self.jog_down_button.bind("<ButtonRelease-1>", self.jog_off)

        self.fix_grid(jog_frame)

        status_frame = Frame(self, background='gray')
        status_frame.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5)

        status_label = Label(status_frame,
                             text='Tester Status',
                             background='gray',
                             font=('Courier', 22, 'bold'),
                             justify=LEFT)
        status_label.configure(font=ul_bold_font)
        status_label.pack(anchor=CENTER, side=TOP, padx=5, pady=5)

        self.status_disp = Text(status_frame)
        self.status_disp.pack(side=TOP, fill=BOTH, padx=5, pady=5)
        self.status_disp.configure(state='disabled')

        self.power_button = Button(status_frame,
                                   text='POWER OFF',
                                   font=('Courier', 24, 'bold'),
                                   background="red",
                                   activebackground="red",
                                   command=self.shutdown,
                                   height=2)
        self.power_button.pack(side=TOP, fill=BOTH, padx=5, pady=5)

    def fix_grid(self, target_frame):
        [columns, rows] = target_frame.grid_size()
        for i in range(rows):
            target_frame.rowconfigure(i, weight=1)
        for j in range(columns):
            target_frame.columnconfigure(j, weight=1)

    def detect_debug_mode(self):
        if str(sys.argv[0]) == 'debug':
            self.update_status('Tester is in debug mode.', 'newline')
            self.update_status('', 'newline')
            self.update_status('The tester will run with a 6 second',
                               'newline')
            self.update_status('  soak time regardless of the soak', 'newline')
            self.update_status('  time selected in the GUI.', 'newline')
            self.debug_mode = True
        else:
            self.update_status('Welcome to the Liquid Thermal Shock',
                               'newline')
            self.update_status('  Tester. Select the number of', 'newline')
            self.update_status('  cycles and the soak time per cycle',
                               'newline')
            self.update_status('  to begin testing. Please ensure', 'newline')
            self.update_status('  that the limit switches are free', 'newline')
            self.update_status('  from obstructions prior to running',
                               'newline')
            self.update_status('  a test.', 'newline')
            self.debug_mode = False

    def cycles_increment(self):
        """ Increments the number of cycles per test. """

        str_num_cycles = self.cycles_select_disp.cget('text')
        num_cycles = int(str_num_cycles)
        num_cycles += 1
        self.cycles_select_disp.configure(text=str(num_cycles))

    def cycles_decrement(self):
        """ Decrements the number of cycles per test. """

        str_num_cycles = self.cycles_select_disp.cget('text')
        num_cycles = int(str_num_cycles)

        # Check for attempts to set num_cycles < 1.
        if num_cycles <= 1:
            self.cycles_select_disp.configure(text=str(num_cycles))
        else:
            num_cycles -= 1
            self.cycles_select_disp.configure(text=str(num_cycles))

    def soak_time_increment(self):
        """ Increments the soak time. """

        str_soak_time = self.soak_time_disp.cget('text')
        soak_time = int(str_soak_time)
        soak_time += 1
        self.soak_time_disp.configure(text=str(soak_time))
        self.reset_timer()

    def soak_time_decrement(self):
        """ Decrements the soak time. """

        str_soak_time = self.soak_time_disp.cget('text')
        soak_time = int(str_soak_time)

        # Check for attempts to set soak time < 1.
        if soak_time <= 1:
            self.soak_time_disp.configure(text=str(soak_time))
        else:
            soak_time -= 1
            self.soak_time_disp.configure(text=str(soak_time))
        self.reset_timer()

    def reset_timer(self):
        """ Resets the timer to whatever is displayed in the
            soak time window."""

        str_soak_time = self.soak_time_disp.cget('text')

        if self.debug_mode:
            self.timer = [0, 6]
        else:
            self.timer = [int(str_soak_time), 0]

        # Use line below for tester debugging -- forces a 5 second soak time.
        # Comment out for normal operations.
        # self.timer = [0, 5]

    # Callback functions for manual motor jog
    def jog_off(self, event):
        motors_off()

    def jog_up_on(self, event):
        jog_motor('up')

    def jog_down_on(self, event):
        jog_motor('down')

    def jog_left_on(self, event):
        jog_motor('left')

    def jog_right_on(self, event):
        jog_motor('right')

    def shutdown(self):
        """ Shuts down the tester. """

        motors_off()
        confirm_string = "Do you really want to power down the tester?"
        confirm = tkMessageBox.askokcancel("Shutdown", confirm_string)
        if confirm:
            subprocess.call("sudo poweroff", shell=True)
        else:
            pass

    def update_status(self, new_text, writemode):
        """ Prints text to the tester status window. """

        self.status_disp.configure(state='normal')
        if writemode == 'overwrite':
            self.status_disp.delete('end-1c linestart', 'end')
        self.status_disp.insert('end', '\n' + new_text)
        self.status_disp.see(END)
        self.status_disp.configure(state='disabled')

    def append_event(self, cycle, type, destination, direction, steps,
                     duration):
        """ Add new event (motor move or temperature soak) to event schedule. """

        self.event_schedule.append({
            'Cycle': cycle,
            'Event type': type,
            'Destination': destination,
            'Direction': direction,
            'Steps': steps,
            'Duration': duration
        })

    def start_homing_move(self, direction):
        """ Starts the homing procedure in the given direction. """

        self.update_status('Finding ' + direction + ' home position...',
                           'newline')
        self.status_disp.update()
        self.home_result.set(0)
        self.queue = Queue.Queue()
        Find_Home_Nonblocking(self.queue, direction).start()
        self.master.after(100, self.process_homing_queue)
        self.wait_variable(self.home_result)

        if self.home_result.get() == 0:
            self.update_status('Homing error. Test aborted.', 'newline')
            return
        else:
            self.update_status(
                direction.capitalize() + ' home position found.', 'newline')

    def run_init(self):
        """ Run button callback.  
        
            Collects run parameters, creates event schedule, then runs the 
            series of scheduled events.
        """

        self.set_state_running()

        # Set number of steps for each motor move. Depends on motor resolution
        # set in static variables section.
        up_steps = self.up_full_steps * (2**self.move_motor_resolution)
        right_steps = self.right_full_steps * (2**self.move_motor_resolution)

        # Get the total number of cycles
        total_cycles_str = self.cycles_select_disp.cget('text')
        total_cycles_int = int(total_cycles_str)

        # Get the soak time in minutes. This is forced to 0.1 minutes when
        # the GUI is launched in debug mode
        if self.debug_mode:
            soak_time_str = '0.1'
            soak_time_float = 0.1
        else:
            soak_time_str = self.soak_time_disp.cget('text')
            soak_time_float = float(soak_time_str)

        # Build event schedule
        self.event_schedule = []
        for i in range(1, total_cycles_int + 1):
            self.append_event(i, 'move', 'hot', 'down', up_steps,
                              up_steps / 2000.0)
            self.append_event(i, 'soak', 'hot', '', '', soak_time_float)
            self.append_event(i, 'move', 'cold', 'up', up_steps,
                              up_steps / 2000.0)
            self.append_event(i, 'move', 'cold', 'left', right_steps,
                              right_steps / 2000.0)
            self.append_event(i, 'move', 'cold', 'down', up_steps,
                              up_steps / 2000.0)
            self.append_event(i, 'soak', 'cold', '', '', soak_time_float)
            self.append_event(i, 'move', 'hot', 'up', up_steps,
                              up_steps / 2000.0)
            self.append_event(i, 'move', 'hot', 'right', right_steps,
                              right_steps / 2000.0)

        # Set the destination to 'complete' for the final 'up' and 'right' moves.
        # Edit the 'Steps' parameter of the final move to end the test in the
        # center of the rail.
        self.event_schedule[-2]['Destination'] = 'complete'
        self.event_schedule[-1]['Destination'] = 'complete'
        self.event_schedule[-1]['Steps'] = right_steps / 2
        self.event_schedule[-1][
            'Duration'] = self.event_schedule[-1]['Steps'] / 2000.0

        self.test_active = True

        # Print initial runtime message to status window
        if soak_time_float == 1.0:
            soak_time_out = '1 minute'
        else:
            soak_time_out = soak_time_str + ' minutes'

        self.update_status('', 'newline')
        self.update_status('Test started.', 'newline')
        out_string = 'The tester will run for ' + total_cycles_str + ' cycles, '
        self.update_status(out_string, 'newline')
        out_string = soak_time_out + ' per cycle.'
        self.update_status(out_string, 'newline')

        if self.test_active == True:
            self.start_homing_move('up')
        if self.test_active == True and self.home_result.get() == 1:
            self.start_homing_move('right')

        if self.test_active == True and self.home_result.get() == 1:
            self.update_status('Moving to hot position...', 'newline')
            self.run_scheduled_events()

    def run_scheduled_events(self):
        """ Runs the series of events listed in self.event_schedule. """

        if self.test_active == True:

            current_event = self.event_schedule.pop(0)

            if current_event['Event type'] == 'soak':
                self.set_state_running()
                self.reset_timer()
                cycle = str(current_event['Cycle'])
                temperature = current_event['Destination']
                self.timer_active.set(1)
                self.countdown_timer(cycle, temperature)
                self.wait_variable(self.timer_active)

            elif current_event['Event type'] == 'move':

                if current_event['Direction'] == 'up':
                    self.set_state_running()
                    if current_event['Destination'] == 'complete':
                        out_string = 'Test complete, moving to neutral '
                        out_string += '      position...'
                        self.update_status(out_string, 'newline')
                    else:
                        out_string = 'Moving to ' + current_event['Destination']
                        out_string += ' position...'
                        self.update_status(out_string, 'newline')

                elif current_event['Direction'] == 'down':
                    self.set_state_running()

                else:
                    self.pause_button.config(state='normal')
                    self.move_direction = current_event['Direction']
                    self.move_total_duration = current_event['Duration']
                    self.planned_steps = current_event['Steps']

                #self.move_result.set(0)
                self.queue = Queue.Queue()
                self.move_started_time = datetime.now()
                Move_Motor_Nonblocking(self.queue, current_event['Direction'],
                                       self.move_motor_resolution,
                                       current_event['Steps']).start()
                self.master.after(100, self.process_move_queue)
                self.wait_variable(self.move_result)
                motors_off()

        # If there are any events left in the schedule, run the next scheduled
        # event.  If there are no events left in the schedule and the last event
        # was a completed move, then the test is complete and this function should
        # output the 'test complete' message.  If there are no events in the schedule
        # and the last event was not a completed move, then the test is paused and
        # this function should do nothing else.
        if self.event_schedule:
            self.after(1000, self.run_scheduled_events)
        elif self.move_result.get() == 1:
            self.update_status('Test complete.', 'overwrite')
            self.set_state_stopped()
        else:
            pass

    def set_state_running(self):
        """ Deactivates cycle time select, soak time select, motor jog
            and power off buttons.

            This is to stop users from changing test parameters during a
            running test, which could result in some difficult to handle
            undefined states.
        """

        self.cycles_increase_button.config(state='disabled')
        self.cycles_decrease_button.config(state='disabled')
        self.soak_time_increment_button.config(state='disabled')
        self.soak_time_decrement_button.config(state='disabled')
        self.run_button.config(state='disabled')
        self.jog_up_button.config(state='disabled')
        self.jog_down_button.config(state='disabled')
        self.jog_left_button.config(state='disabled')
        self.jog_right_button.config(state='disabled')
        self.power_button.config(state='disabled')
        self.pause_button.config(state='disabled')

        # This is absurd, but apparently setting a button to 'disabled' does
        # not actually disable the button event bindings, so binding the buttons
        # to a 'do_nothing()' function is required.
        self.jog_up_button.bind("<Button-1>", self.do_nothing)
        self.jog_up_button.bind("<ButtonRelease-1>", self.do_nothing)
        self.jog_down_button.bind("<Button-1>", self.do_nothing)
        self.jog_down_button.bind("<ButtonRelease-1>", self.do_nothing)
        self.jog_left_button.bind("<Button-1>", self.do_nothing)
        self.jog_left_button.bind("<ButtonRelease-1>", self.do_nothing)
        self.jog_right_button.bind("<Button-1>", self.do_nothing)
        self.jog_right_button.bind("<ButtonRelease-1>", self.do_nothing)

    def set_state_stopped(self):
        """ Reactivates all of the buttons deactivated in the
            set_state_running function.
        """

        self.test_active = False
        self.test_paused = False

        self.cycles_increase_button.config(state='normal')
        self.cycles_decrease_button.config(state='normal')
        self.soak_time_increment_button.config(state='normal')
        self.soak_time_decrement_button.config(state='normal')
        self.run_button.config(state='normal')
        self.jog_up_button.config(state='normal')
        self.jog_down_button.config(state='normal')
        self.jog_left_button.config(state='normal')
        self.jog_right_button.config(state='normal')
        self.power_button.config(state='normal')
        self.pause_button.config(state='disabled')
        self.pause_button.config(text='PAUSE',
                                 background='orange',
                                 activebackground='orange')

        self.jog_up_button.bind("<Button-1>", self.jog_up_on)
        self.jog_up_button.bind("<ButtonRelease-1>", self.jog_off)
        self.jog_down_button.bind("<Button-1>", self.jog_down_on)
        self.jog_down_button.bind("<ButtonRelease-1>", self.jog_off)
        self.jog_left_button.bind("<Button-1>", self.jog_left_on)
        self.jog_left_button.bind("<ButtonRelease-1>", self.jog_off)
        self.jog_right_button.bind("<Button-1>", self.jog_right_on)
        self.jog_right_button.bind("<ButtonRelease-1>", self.jog_off)

    def do_nothing(self, event):
        """ Does absolutely nothing. This is a workaround for the fact that
            button event bindings are not disabled when a button's state is
            set to 'disabled'.
        """

        pass

    def pause_timer(self):
        """ Displays the running duration of a test pause. """

        if self.test_paused:
            timer_string = '{0:1d}:{1:02d}'.format(self.timer[0],
                                                   self.timer[1])

            out_string = 'Test paused for ' + timer_string
            self.update_status(out_string, 'overwrite')

            self.timer[1] += 1
            if self.timer[1] >= 60:
                self.timer[0] += 1
                self.timer[1] -= 60

            self.after(1000, self.pause_timer)

    def countdown_timer(self, cycle, temperature):
        """ Displays countdown timer and current cycle number/temperature
            information in status window.

            This function will only process if the timer_active flag is set to
            1. The function will then recursively call itself after a 1 second
            wait until the timer_active flag is set to zero.

            The timing is not precise because it will wait 1 full second between
            function calls, and therefore does not take into account the time
            necessary to process the function itself. However, over a typical
            soak time this will only amount to milliseconds, so it's certainly
            close enough for this application.
        """

        if self.timer_active.get() == 1:
            timer_string = '{0:1d}:{1:02d}'.format(self.timer[0],
                                                   self.timer[1])
            out_string = 'Cycle ' + cycle + ' of '
            out_string += self.cycles_select_disp.cget('text') + ', '
            out_string += temperature + '. ' + timer_string + ' remaining.'

            self.update_status(out_string, 'overwrite')

            # Decrement 1 second from timer. If this flips the seconds to a
            # negative value, decrement 1 minute and add 60 seconds
            self.timer[1] -= 1
            if self.timer[1] < 0:
                # If timer is run down to zero, display soak complete message
                # and set timer_active flag to zero.
                if self.timer[0] <= 0:
                    out_string = 'Cycle ' + cycle + ' of '
                    out_string += self.cycles_select_disp.cget('text') + ', '
                    out_string += temperature + ' complete.'
                    self.update_status(out_string, 'overwrite')
                    self.timer_active.set(0)
                else:
                    self.timer[0] -= 1
                    self.timer[1] += 60

            # Have the countdown_timer function recursively call itself
            # after 1000ms.
            self.after(1000, self.countdown_timer, cycle, temperature)

    def stop_test(self):
        """ Stop button callback.  Allows user to abort test sequence. """

        # Clear event schedule and toggle home and move result monitoring
        # variables. This helps prevent errors on restart
        motors_off()

        self.event_schedule = []
        self.home_result.set(0)
        self.move_result.set(0)

        if self.test_active:
            self.update_status('Test stopped by user.', 'newline')

        self.test_active = False

        # Stop and reset timer, reactivate buttons (in case the test
        # needs to be restarted).
        self.timer_active.set(0)
        self.reset_timer()
        self.set_state_stopped()

    def pause_button_pressed(self):
        """ Pause button callback. """

        if self.test_paused:
            self.test_paused = False
            self.resume_test()
        else:
            self.test_paused = True
            self.timer = [0, 0]
            self.pause_test()

    def pause_test(self):
        """ Pauses a running test """

        motors_off()
        self.pause_time = datetime.now()

        self.pause_button.config(text='RESUME',
                                 background='green',
                                 activebackground='green')

        self.resume_schedule = self.event_schedule

        self.event_schedule = []
        self.move_result.set(0)
        pause_delta = self.pause_time - self.move_started_time
        pause_delta_seconds = float(pause_delta.seconds)
        pause_delta_seconds += pause_delta.microseconds / 1000000.0

        steps_prepause = int(pause_delta_seconds * 2000)

        steps_remaining = self.planned_steps - steps_prepause

        move_time_remaining = self.move_total_duration - pause_delta_seconds

        resume_event = {
            'Cycle': '',
            'Event type': 'move',
            'Destination': '',
            'Direction': self.move_direction,
            'Steps': steps_remaining,
            'Duration': move_time_remaining
        }

        self.resume_schedule.insert(0, resume_event)

        self.update_status('', 'newline')
        self.pause_timer()

    def resume_test(self):
        """ Resumes a paused test """

        self.pause_button.config(text='PAUSE',
                                 background='orange',
                                 activebackground='orange')
        self.resume_time = datetime.now()

        self.event_schedule = self.resume_schedule

        pause_duration = self.resume_time - self.pause_time

        pause_duration_seconds = float(pause_duration.seconds)
        pause_duration_seconds += pause_duration.microseconds / 1000000.0

        self.test_active = True
        self.update_status('Test resumed.', 'newline')
        self.run_scheduled_events()

    def process_homing_queue(self):
        """ Checks if homing function has returned a value. """

        # Try to read the first value in the queue. If nothing is there, then
        # the homing function has not yet returned a value and must still be
        # active. In this case, the function recursively calls itself after
        # 100ms. If there is something in the queue, the value is read into
        # the self.home_result variable and the function is not called again.
        try:
            self.home_result.set(self.queue.get(0))
        except Queue.Empty:
            self.master.after(10, self.process_homing_queue)

    def process_move_queue(self):
        """ Checks if motor move queue as returned value. """

        # Try to read the first value in the queue. If nothing is there, then
        # the motor move function has not yet returned a value and must still be
        # active. In this case, the function recursively calls itself after
        # 100ms. If there is something in the queue, the value is read into
        # the self.move_result variable and the function is not called again.

        try:
            self.move_result.set(self.queue.get(0))
        except Queue.Empty:
            self.master.after(100, self.process_move_queue)
class BoardConfig(Frame):

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

        self.parent = master
        self.main = main

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

        self.intvar = IntVar()

        #Arch
        self.arch_var = IntVar()
        lf_arch = LabelFrame(self.parent, text="Architecture")
        lf_arch.pack(fill=X, expand=True, side=TOP)

        frame_arch = Frame(lf_arch)
        frame_arch.pack(fill=X, expand=True, side=TOP)

        frame_left1 = Frame(frame_arch)
        frame_left1.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right1 = Frame(frame_arch)
        frame_right1.pack(expand=True, fill=BOTH, side=RIGHT)

        self.radioButton_arch_8 = Radiobutton(frame_left1, text="8-bit ", anchor="w", width=10, value=8, variable=self.arch_var, command=self.update_mode)
        self.radioButton_arch_8.pack(fill=X, side=TOP)

        self.radioButton_arch_32 = Radiobutton(frame_right1, text="32-bit", anchor="w", width=10, value=32, variable=self.arch_var, command=self.update_mode)
        self.radioButton_arch_32.pack(fill=X, side=TOP)


        #Mode
        self.mode_var = StringVar()
        lf_mode = LabelFrame(self.parent, text="Programming mode")
        lf_mode.pack(fill=X, expand=True, side=TOP)

        frame_mode = Frame(lf_mode)
        frame_mode.pack(fill=X, expand=True, side=TOP)

        frame_left2 = Frame(frame_mode)
        frame_left2.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right2 = Frame(frame_mode)
        frame_right2.pack(expand=True, fill=BOTH, side=RIGHT)

        self.radioButton_mode_icsp = Radiobutton(frame_left2, text="ICSP", anchor="w", width=10, value="icsp", variable=self.mode_var, command=self.update_mode)
        self.radioButton_mode_icsp.pack(side=TOP, fill=X)

        self.radioButton_mode_bootloader = Radiobutton(frame_right2, text="Bootloader", anchor="w", width=10, value="bootloader", variable=self.mode_var, command=self.update_mode)
        self.radioButton_mode_bootloader.pack(side=TOP, fill=X)


        #Bootloader
        self.boot_var = StringVar()
        self.lf_boot = LabelFrame(self.parent, text="Bootloader")
        self.lf_boot.pack(fill=X, expand=True, side=TOP)

        frame_boot = Frame(self.lf_boot)
        frame_boot.pack(fill=X, expand=True, side=TOP)

        frame_left3 = Frame(frame_boot)
        frame_left3.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right3 = Frame(frame_boot)
        frame_right3.pack(expand=True, fill=BOTH, side=RIGHT)

        self.radioButton_bootloader_v1_v2 = Radiobutton(frame_left3, text="v1.x or v2.x", anchor="w", width=10, value="v1_v2", variable=self.boot_var)
        self.radioButton_bootloader_v1_v2.pack(fill=X, side=TOP, expand=True)
        self.radioButton_bootloader_v4 = Radiobutton(frame_right3, text="v4.x", anchor="w", width=10, value="v4", variable=self.boot_var)
        self.radioButton_bootloader_v4.pack(fill=X, side=TOP, expand=True)


        #Devices 8bit
        self.dev8_var = StringVar()
        self.lf_dev8 = LabelFrame(self.parent, text="Devices")
        self.lf_dev8.pack(fill=X, expand=True, side=TOP)

        self.frame_8b = Frame(self.lf_dev8)
        self.frame_8b.pack(fill=X, expand=True, side=TOP)


        #Devices 32bit
        self.dev32_var = StringVar()
        self.lf_dev32 = LabelFrame(self.parent, text="Devices")
        self.lf_dev32.pack(fill=X, expand=True, side=TOP)

        self.frame_32b = Frame(self.lf_dev32)
        self.frame_32b.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=RIGHT)
        Button(frame_buttons, text="Cancel", command=self.quit).pack(fill=X, expand=True, side=LEFT)
        frame_buttons.pack(fill=X, expand=True, side=BOTTOM)

        frame_advance = Frame(self.parent)
        self.advanceoptions = Button(frame_advance, text="Advance options", command=self.advance)
        self.advanceoptions.pack(fill=X, expand=True, side=BOTTOM)
        frame_advance.pack(fill=X, expand=True, side=BOTTOM)

        frame_warning = Frame(self.parent)
        self.label_warning = Label(frame_warning, fg="red", text="warning!", anchor="w")
        self.label_warning.pack(fill=X, expand=True, side=BOTTOM)
        frame_warning.pack(fill=X, expand=True, side=BOTTOM)

        self.build_devices_arch()
        self.load_config()
        self.init_groups()




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

        self.master.destroy()


    #----------------------------------------------------------------------
    def build_devices_arch(self):

        #8bits
        name_checked = self.main.configIDE.config("Board", "board_8", "Pinguino 2550")
        arch_8 = filter(lambda board:board.arch==8, self.main.pinguinoAPI._boards_)
        arch_8.sort()

        frame_left = Frame(self.frame_8b)
        frame_left.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right = Frame(self.frame_8b)
        frame_right.pack(expand=True, fill=BOTH, side=RIGHT)

        parent = frame_left  #left
        for board in arch_8:
            if arch_8.index(board) == (len(arch_8) / 2) + 1:
                parent = frame_right  #rigth

            radio = Radiobutton(parent, text=board.name, anchor="w", width=10, value=board.name, variable=self.dev8_var, command=lambda :self.set_board_name(board.name, "8"))
            radio.pack(expand=True, fill=X, side=TOP)

            #radio = QtGui.QRadioButton(self.board_config.groupBox_devices_8)
            #self.board_config.gridLayout_device_8.addWidget(radio, count, side, 1, 1)
            #radio.setText(board.name)
            #radio.setToolTip(board.proc)

            if name_checked == board.name: radio.select()
            #self.connect(radio, QtCore.SIGNAL("clicked()"), self.set_board_name(board.name, "8"))


        #32bits
        name_checked = self.main.configIDE.config("Board", "board_32", "PIC32 Pinguino OTG")
        arch_32 = filter(lambda board:board.arch==32, self.main.pinguinoAPI._boards_)
        arch_32.sort()

        frame_left0 = Frame(self.frame_32b)
        frame_left0.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right0 = Frame(self.frame_32b)
        frame_right0.pack(expand=True, fill=BOTH, side=RIGHT)

        parent = frame_left0  #left
        for board in arch_32:
            if arch_32.index(board) == (len(arch_32) / 2) + 1:
                parent = frame_right0  #rigth

            radio = Radiobutton(parent, text=board.name, anchor="w", width=10, value=board.name, variable=self.dev32_var, command=lambda :self.set_board_name(board.name, "32"))
            radio.pack(expand=True, fill=X, side=TOP)

            #radio = QtGui.QRadioButton(self.board_config.groupBox_devices_32)
            #self.board_config.gridLayout_device_32.addWidget(radio, count, side, 1, 1)
            #radio.setText(board.name)
            #radio.setToolTip(board.proc)

            if name_checked == board.name: radio.select()
            #self.connect(radio, QtCore.SIGNAL("clicked()"), self.set_board_name(board.name, "32"))



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

        self.main.configIDE.load_config()

        arch = self.main.configIDE.config("Board", "arch", 8)
        getattr(self.radioButton_arch_8, "select" if (arch == 8) else "deselect")()
        getattr(self.radioButton_arch_32, "select" if (arch == 32) else "deselect")()

        if arch == 32: self.advanceoptions.pack(fill=X, expand=True, side=BOTTOM)
        else: self.advanceoptions.forget()

        mode = self.main.configIDE.config("Board", "mode", "bootloader")
        getattr(self.radioButton_mode_bootloader, "select" if (mode == "bootloader") else "deselect")()
        getattr(self.radioButton_mode_icsp, "select" if (mode == "icsp") else "deselect")()

        bootloader = self.main.configIDE.config("Board", "bootloader", "v1_v2")
        getattr(self.radioButton_bootloader_v1_v2, "select" if (bootloader == "v1_v2") else "deselect")()
        getattr(self.radioButton_bootloader_v4, "select" if (bootloader == "v4") else "deselect")()

        self.update_mode()


    #----------------------------------------------------------------------
    def update_mode(self):

        mode_boot = self.mode_var.get() == "bootloader"
        arch_8 = self.arch_var.get() == 8

        if mode_boot and arch_8: self.lf_boot.pack(fill=X, expand=True, side=TOP)
        else: self.lf_boot.forget()
        self.init_groups()

        if not mode_boot:
            self.label_warning.configure(text="WARNING!! this mode can overwite the bootloader code.")
        else:
            self.label_warning.configure(text="")



    #----------------------------------------------------------------------
    def set_board_name(self, name, arch):

        def dummy():
            self.main.configIDE.set("Board", "board_"+arch, name)
        return dummy


    #----------------------------------------------------------------------
    def init_groups(self):

        self.lf_dev32.forget()
        self.lf_dev8.forget()

        if self.arch_var.get() == 8:
            self.lf_dev8.pack(fill=X, expand=True, side=TOP)
            self.advanceoptions.forget()

        else:
            self.lf_dev32.pack(fill=X, expand=True, side=TOP)
            self.advanceoptions.pack(fill=X, expand=True, side=BOTTOM)



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

        #if self.board_config.radioButton_arch_8.isChecked(): arch = 8
        #else: arch = 32
        self.main.configIDE.set("Board", "arch", self.arch_var.get())

        #if self.board_config.radioButton_mode_bootloader.isChecked(): mode = "bootloader"
        #else: mode = "icsp"
        self.main.configIDE.set("Board", "mode", self.mode_var.get())

        #if self.board_config.radioButton_bootloader_v1_v2.isChecked(): bootloader = "v1_v2"
        #else: bootloader = "v4"
        self.main.configIDE.set("Board", "bootloader", self.boot_var.get())

        name = self.main.configIDE.config("Board", "board_"+str(self.arch_var.get()), None)
        self.main.configIDE.set("Board", "board", name)



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

        self.save_config()
        self.main.configIDE.save_config()
        self.main.statusbar_ide(self.main.get_status_board())
        self.close_advance()
        self.quit()


    #----------------------------------------------------------------------
    def advance(self):

        root = Toplevel()
        self.frame_advance = BoardConfigAdvance(master=root, main=self.main)
        self.frame_advance.mainloop()


    #----------------------------------------------------------------------
    def close_advance(self):

        try: assert self.frame_advance
        except: return
        self.frame_advance.quit()
Example #22
0
class MainWindow(object):

    def __init__(self, root, data, interval, font_face, font_size, on_top):
        # GUI display
        self.root = root
        frame = Frame(root)
        frame.pack()

        font = (font_face, font_size)
        self.card = Label(frame, font=font)
        self.card.pack()

        # Card refresh interval, in seconds
        self.refresh_interval = interval

        # Data for tracking
        self.data = data
        self.pending = []
        self.current = None

        # Update card tracking
        self.reset_card()
        self.update_card()

        if on_top:
            self.root.wm_attributes("-topmost", 1)

        # Bind events
        self.root.bind("<Button-1>", self.flip_forward)
        self.root.bind("<Key-Return>", self.flip_forward)
        self.root.bind("<Key-space>", self.flip_forward)

        self.root.bind("<Button-3>", self.flip_backward)
        self.root.bind("<Key-BackSpace>", self.flip_backward)

    def reset_card(self):
        """
        Resets the pending list of cards.

        This method will automatically filter out duplicate entries.

        """
        self.pending = list(set(self.data[:]))

    def pull_next_card(self):
        """
        Pulls the next card from the card list.

        This method tracks the current card and will avoid pulling
        the same card two times in a row (unless there's only one
        card left to pull).

        Returns the next card.  The value is also set as
        self.current.

        """
        card = self.current
        if len(self.pending) < 1:
            raise EmptyList()
        elif len(self.pending) == 1:
            index = 0
            card = self.pending[0]
        else:
            while card == self.current:
                index = random.randint(0, len(self.pending) - 1)
                card = self.pending[index]

        del self.pending[index]

        if len(self.pending) < 1:
            self.reset_card()

        self.current = card
        self.current_index = 0
        return card

    def update_card(self):
        """
        Pulls the next card and updates the GUI.

        This is a self-recurring call.  It should only be called at
        the beginning of the application.

        """
        card = self.pull_next_card()
        self.card.configure(text=card[0])

        refresh_ms = int(self.refresh_interval * 1000)
        self.root.after(refresh_ms, self.update_card)

    def flip_forward(self, event):
        self.current_index = (self.current_index + 1) % len(self.current)
        self.card.configure(text=self.current[self.current_index])

    def flip_backward(self, event):
        self.current_index = (self.current_index - 1) % len(self.current)
        self.card.configure(text=self.current[self.current_index])
Example #23
0
class PinguinoIDE(Frame, PinguinoEvents):

    def __init__(self, master=None):

        Frame.__init__(self, master)

        self.parent = master

        self.parent.geometry("640x480")
        self.parent.title(os.getenv("NAME"))

        icon = os.path.join(os.getcwd(), "tkgui", "resources", "art", "pinguino11.xbm")
        self.parent.wm_iconbitmap("@"+icon)

        TkStyles.create_styles()
        self.Files = {}

        PinguinoConfig.set_environ_vars()
        PinguinoConfig.check_user_files()

        self.pinguinoAPI = Pinguino()
        self.pinguinoAPI._boards_ = AllBoards

        self.configIDE = Config()

        PinguinoConfig.update_pinguino_paths(self.configIDE, self.pinguinoAPI)
        PinguinoConfig.update_pinguino_extra_options(self.configIDE, self.pinguinoAPI)
        PinguinoConfig.update_user_libs(self.pinguinoAPI)
        self.pinguinoAPI.set_os_variables()

        self.set_board()

        self.build_menu()

        self.buil_output()
        self.build_status_bar()
        self.buil_toolbar()
        self.build_notebook()
        self.connect_events()

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

        self.parent.config(menu=self.menuBar)


        os_name = os.getenv("PINGUINO_OS_NAME")
        if os_name == "windows":
            os.environ["PATH"] = os.environ["PATH"] + ";" + self.configIDE.get_path("sdcc_bin")

        elif os_name == "linux":
            os.environ["LD_LIBRARY_PATH"]="/usr/lib32:/usr/lib:/usr/lib64"


    #----------------------------------------------------------------------
    def build_status_bar(self):

        frame_status = Frame(self.parent, height=18)
        frame_status.pack(side=BOTTOM, expand=False, fill=X)

        self.label_status_bar = Label(frame_status, anchor="w", text=self.get_status_board())
        self.label_status_bar.pack(expand=True, fill=X, side=TOP)


    #----------------------------------------------------------------------
    def statusbar_ide(self, message):

        self.label_status_bar.configure(text=message)


    #----------------------------------------------------------------------
    def build_notebook(self):

        banner = os.path.join("tkgui", "resources", "art", "banner.png")
        tkimage = ImageTk.PhotoImage(file=banner)
        self.banner = Label(self, image=tkimage, justify = CENTER, height = 400, bg="#afc8e1")
        self.banner.photo = tkimage
        self.banner.pack(side=LEFT, fill=BOTH, expand=True)

        self.noteBook = Notebook(self, style="TNotebook")
        #self.noteBook.pack(side=LEFT, fill=BOTH, expand=True)


    #----------------------------------------------------------------------
    def build_menu(self):

        self.menuBar = Menu(self, borderwidth=1, relief=FLAT)

        filemenu = Menu(self.menuBar, tearoff=0)
        filemenu.add_command(label="New", command=self.new_file, accelerator="Ctrl+N")
        filemenu.add_command(label="Open", command=self.open_file, accelerator="Ctrl+O")
        filemenu.add_separator()
        filemenu.add_command(label="Save file", command=self.save_file, accelerator="Ctrl+S")
        filemenu.add_command(label="Save as", command=self.save_as)
        filemenu.add_separator()
        filemenu.add_command(label="Close", command=self.close_file, accelerator="Ctrl+W")
        filemenu.add_command(label="Close all", command=self.close_all)
        filemenu.add_separator()
        filemenu.add_command(label="Quit", command=self.close_ide, accelerator="Ctrl+Q")
        self.menuBar.add_cascade(label="File", menu=filemenu)


        editmenu = Menu(self.menuBar, tearoff=0)
        editmenu.add_command(label="Undo", command=self.edit_undo, accelerator="Ctrl+Z")
        editmenu.add_command(label="Redo", command=self.edit_redo, accelerator="Ctrl+Y")
        editmenu.add_separator()
        editmenu.add_command(label="Cut", command=self.edit_cut, accelerator="Ctrl+X")
        editmenu.add_command(label="Copy", command=self.edit_copy, accelerator="Ctrl+C")
        editmenu.add_command(label="Paste", command=self.edit_paste, accelerator="Ctrl+V")
        self.menuBar.add_cascade(label="Edit", menu=editmenu)

        configmenu = Menu(self.menuBar, tearoff=0)
        configmenu.add_command(label="Board Settings", command=self.__show_board_config__)
        configmenu.add_command(label="System paths", command=self.__show_paths__)
        self.menuBar.add_cascade(label="Configuration", menu=configmenu)

        pinguinomenu = Menu(self.menuBar, tearoff=0)
        pinguinomenu.add_command(label="Compile", command=self.pinguino_compile, accelerator="F5")
        pinguinomenu.add_command(label="Upload", command=self.pinguino_upload, accelerator="F6")
        pinguinomenu.add_separator()
        pinguinomenu.add_command(label="Stdout", command=self.__show_stdout__, accelerator="F9")
        self.menuBar.add_cascade(label="Pinguino", menu=pinguinomenu)

        self.menuBar.add_cascade(label="Examples", menu=self.examples_view())

        helpmenu = Menu(self.menuBar, tearoff=0)
        links = Menu(helpmenu, tearoff=0)
        github = Menu(links, tearoff=0)
        github.add_command(label="IDE", command=lambda :self.open_web_site("https://github.com/PinguinoIDE/pinguino-ide/releases/latest"))
        github.add_command(label="Libraries", command=lambda :self.open_web_site("https://github.com/PinguinoIDE/pinguino-libraries/releases/latest"))
        github.add_command(label="Compilers", command=lambda :self.open_web_site("https://github.com/PinguinoIDE/pinguino-compilers/releases/latest"))
        links.add_cascade(label="GitHub", menu=github)
        links.add_command(label="Website", command=lambda :self.open_web_site("http://www.pinguino.cc/"))
        links.add_command(label="Wiki", command=lambda :self.open_web_site("http://wiki.pinguino.cc/"))
        links.add_command(label="Forum", command=lambda :self.open_web_site("http://forum.pinguino.cc/"))
        links.add_command(label="Blog", command=lambda :self.open_web_site("http://blog.pinguino.cc/"))
        links.add_command(label="Group", command=lambda :self.open_web_site("https://groups.google.com/forum/#!forum/pinguinocard"))
        links.add_command(label="Shop", command=lambda :self.open_web_site("http://shop.pinguino.cc/"))
        helpmenu.add_cascade(label="Links", menu=links)
        helpmenu.add_command(label="About...", command=self.__show_about__)
        self.menuBar.add_cascade(label="Help", menu=helpmenu)

        self.master.bind_all("<Control-n>", self.new_file)
        self.master.bind_all("<Control-o>", self.open_file)
        self.master.bind_all("<Control-s>", self.save_file)
        self.master.bind_all("<Control-w>", self.close_file)
        self.master.bind_all("<Control-q>", self.close_ide)

        self.master.bind_all("<Control-Z>", self.edit_undo)
        self.master.bind_all("<Control-Y>", self.edit_redo)

        self.master.bind_all("<Control-X>", self.edit_cut)
        self.master.bind_all("<Control-C>", self.edit_copy)
        self.master.bind_all("<Control-V>", self.edit_paste)

        self.master.bind_all("<F5>", self.pinguino_compile)
        self.master.bind_all("<F6>", self.pinguino_upload)
        self.master.bind_all("<F9>", self.__show_stdout__)


    #----------------------------------------------------------------------
    def examples_view(self):

        examplesmenu = Menu(self.menuBar, tearoff=0)
        return self.process_directory(examplesmenu, os.path.join(os.getenv("PINGUINO_USER_PATH"), "examples"))


    #----------------------------------------------------------------------
    def process_directory(self, parent, path):

        menu = Menu(parent, tearoff=0)
        for p in os.listdir(path):
            abspath = os.path.join(path, p)

            if os.path.isfile(abspath):
                if abspath.endswith(".pde"):
                    label = os.path.split(abspath)[1]
                    #menu.add_command(label=label, command=lambda :self.open_file(abspath))
                    menu.add_command(label=label, command=self.open_file_example_event(abspath))

            if os.path.isdir(abspath):
                label = os.path.split(abspath)[1]
                menu.add_cascade(label=label, menu=self.process_directory(menu, abspath))

        return menu

    #----------------------------------------------------------------------
    def open_file_example_event(self, filename):

        def intern_f():
            self.open_file(filename)
        return intern_f

    #----------------------------------------------------------------------
    def buil_toolbar(self):

        Separator(self, style="TSeparator").pack(side=TOP, fill=X, expand=False)

        self.toolBar = Frame(self, borderwidth=0, relief=FLAT, highlightthickness=0)
        self.toolBar.pack(side=TOP, fill=X, expand=False)

        Frame(self, height=4, bg="#afc8e1").pack(side=TOP, fill=X, expand=False)


    #----------------------------------------------------------------------
    def buil_output(self):

        self.output = Text(self, bg="#333333", fg="#ffffff", height=10, borderwidth=0, relief=FLAT, highlightthickness=0, font="mono 10")
        HEAD = os.getenv("NAME") + " " + os.getenv("VERSION") + "\n"
        self.output.pack(side=BOTTOM, fill=X, expand=False)
        self.output.insert(END, "\n "+HEAD)
        self.output.config(state=DISABLED)

        Frame(self, height=4, bg="#afc8e1").pack(side=BOTTOM, fill=X, expand=False)


    #----------------------------------------------------------------------
    def write_log(self, *args, **kwargs):

        lines = " "
        for line in args:
            lines += line + "\n"

        for key in kwargs.keys():
            line = key + ": " + kwargs[key]
            lines += line

        self.output.config(state=NORMAL)
        self.output.insert(END, lines.replace("\n", "\n ")[:-1])
        self.output.see(END)
        self.output.config(state=DISABLED)
Example #24
0
class BoardConfig(Frame):
    def __init__(self, master=None, main=None):
        Frame.__init__(self, master)

        self.parent = master
        self.main = main

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

        self.intvar = IntVar()

        #Arch
        self.arch_var = IntVar()
        lf_arch = LabelFrame(self.parent, text="Architecture")
        lf_arch.pack(fill=X, expand=True, side=TOP)

        frame_arch = Frame(lf_arch)
        frame_arch.pack(fill=X, expand=True, side=TOP)

        frame_left1 = Frame(frame_arch)
        frame_left1.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right1 = Frame(frame_arch)
        frame_right1.pack(expand=True, fill=BOTH, side=RIGHT)

        self.radioButton_arch_8 = Radiobutton(frame_left1,
                                              text="8-bit ",
                                              anchor="w",
                                              width=10,
                                              value=8,
                                              variable=self.arch_var,
                                              command=self.update_mode)
        self.radioButton_arch_8.pack(fill=X, side=TOP)

        self.radioButton_arch_32 = Radiobutton(frame_right1,
                                               text="32-bit",
                                               anchor="w",
                                               width=10,
                                               value=32,
                                               variable=self.arch_var,
                                               command=self.update_mode)
        self.radioButton_arch_32.pack(fill=X, side=TOP)

        #Mode
        self.mode_var = StringVar()
        lf_mode = LabelFrame(self.parent, text="Programming mode")
        lf_mode.pack(fill=X, expand=True, side=TOP)

        frame_mode = Frame(lf_mode)
        frame_mode.pack(fill=X, expand=True, side=TOP)

        frame_left2 = Frame(frame_mode)
        frame_left2.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right2 = Frame(frame_mode)
        frame_right2.pack(expand=True, fill=BOTH, side=RIGHT)

        self.radioButton_mode_icsp = Radiobutton(frame_left2,
                                                 text="ICSP",
                                                 anchor="w",
                                                 width=10,
                                                 value="icsp",
                                                 variable=self.mode_var,
                                                 command=self.update_mode)
        self.radioButton_mode_icsp.pack(side=TOP, fill=X)

        self.radioButton_mode_bootloader = Radiobutton(
            frame_right2,
            text="Bootloader",
            anchor="w",
            width=10,
            value="bootloader",
            variable=self.mode_var,
            command=self.update_mode)
        self.radioButton_mode_bootloader.pack(side=TOP, fill=X)

        #Bootloader
        self.boot_var = StringVar()
        self.lf_boot = LabelFrame(self.parent, text="Bootloader")
        self.lf_boot.pack(fill=X, expand=True, side=TOP)

        frame_boot = Frame(self.lf_boot)
        frame_boot.pack(fill=X, expand=True, side=TOP)

        frame_left3 = Frame(frame_boot)
        frame_left3.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right3 = Frame(frame_boot)
        frame_right3.pack(expand=True, fill=BOTH, side=RIGHT)

        self.radioButton_bootloader_v1_v2 = Radiobutton(frame_left3,
                                                        text="v1.x or v2.x",
                                                        anchor="w",
                                                        width=10,
                                                        value="v1_v2",
                                                        variable=self.boot_var)
        self.radioButton_bootloader_v1_v2.pack(fill=X, side=TOP, expand=True)
        self.radioButton_bootloader_v4 = Radiobutton(frame_right3,
                                                     text="v4.x",
                                                     anchor="w",
                                                     width=10,
                                                     value="v4",
                                                     variable=self.boot_var)
        self.radioButton_bootloader_v4.pack(fill=X, side=TOP, expand=True)

        #Devices 8bit
        self.dev8_var = StringVar()
        self.lf_dev8 = LabelFrame(self.parent, text="Devices")
        self.lf_dev8.pack(fill=X, expand=True, side=TOP)

        self.frame_8b = Frame(self.lf_dev8)
        self.frame_8b.pack(fill=X, expand=True, side=TOP)

        #Devices 32bit
        self.dev32_var = StringVar()
        self.lf_dev32 = LabelFrame(self.parent, text="Devices")
        self.lf_dev32.pack(fill=X, expand=True, side=TOP)

        self.frame_32b = Frame(self.lf_dev32)
        self.frame_32b.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=RIGHT)
        Button(frame_buttons, text="Cancel",
               command=self.quit).pack(fill=X, expand=True, side=LEFT)
        frame_buttons.pack(fill=X, expand=True, side=BOTTOM)

        frame_advance = Frame(self.parent)
        self.advanceoptions = Button(frame_advance,
                                     text="Advance options",
                                     command=self.advance)
        self.advanceoptions.pack(fill=X, expand=True, side=BOTTOM)
        frame_advance.pack(fill=X, expand=True, side=BOTTOM)

        frame_warning = Frame(self.parent)
        self.label_warning = Label(frame_warning,
                                   fg="red",
                                   text="warning!",
                                   anchor="w")
        self.label_warning.pack(fill=X, expand=True, side=BOTTOM)
        frame_warning.pack(fill=X, expand=True, side=BOTTOM)

        self.build_devices_arch()
        self.load_config()
        self.init_groups()

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

        self.master.destroy()

    #----------------------------------------------------------------------
    def build_devices_arch(self):

        #8bits
        name_checked = self.main.configIDE.config("Board", "board_8",
                                                  "Pinguino 2550")
        arch_8 = filter(lambda board: board.arch == 8,
                        self.main.pinguinoAPI._boards_)
        arch_8.sort()

        frame_left = Frame(self.frame_8b)
        frame_left.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right = Frame(self.frame_8b)
        frame_right.pack(expand=True, fill=BOTH, side=RIGHT)

        parent = frame_left  #left
        for board in arch_8:
            if arch_8.index(board) == (len(arch_8) / 2) + 1:
                parent = frame_right  #rigth

            radio = Radiobutton(
                parent,
                text=board.name,
                anchor="w",
                width=10,
                value=board.name,
                variable=self.dev8_var,
                command=lambda: self.set_board_name(board.name, "8"))
            radio.pack(expand=True, fill=X, side=TOP)

            #radio = QtGui.QRadioButton(self.board_config.groupBox_devices_8)
            #self.board_config.gridLayout_device_8.addWidget(radio, count, side, 1, 1)
            #radio.setText(board.name)
            #radio.setToolTip(board.proc)

            if name_checked == board.name: radio.select()
            #self.connect(radio, QtCore.SIGNAL("clicked()"), self.set_board_name(board.name, "8"))

        #32bits
        name_checked = self.main.configIDE.config("Board", "board_32",
                                                  "PIC32 Pinguino OTG")
        arch_32 = filter(lambda board: board.arch == 32,
                         self.main.pinguinoAPI._boards_)
        arch_32.sort()

        frame_left0 = Frame(self.frame_32b)
        frame_left0.pack(expand=True, fill=BOTH, side=LEFT)

        frame_right0 = Frame(self.frame_32b)
        frame_right0.pack(expand=True, fill=BOTH, side=RIGHT)

        parent = frame_left0  #left
        for board in arch_32:
            if arch_32.index(board) == (len(arch_32) / 2) + 1:
                parent = frame_right0  #rigth

            radio = Radiobutton(
                parent,
                text=board.name,
                anchor="w",
                width=10,
                value=board.name,
                variable=self.dev32_var,
                command=lambda: self.set_board_name(board.name, "32"))
            radio.pack(expand=True, fill=X, side=TOP)

            #radio = QtGui.QRadioButton(self.board_config.groupBox_devices_32)
            #self.board_config.gridLayout_device_32.addWidget(radio, count, side, 1, 1)
            #radio.setText(board.name)
            #radio.setToolTip(board.proc)

            if name_checked == board.name: radio.select()
            #self.connect(radio, QtCore.SIGNAL("clicked()"), self.set_board_name(board.name, "32"))

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

        self.main.configIDE.load_config()

        arch = self.main.configIDE.config("Board", "arch", 8)
        getattr(self.radioButton_arch_8, "select" if
                (arch == 8) else "deselect")()
        getattr(self.radioButton_arch_32, "select" if
                (arch == 32) else "deselect")()

        if arch == 32:
            self.advanceoptions.pack(fill=X, expand=True, side=BOTTOM)
        else:
            self.advanceoptions.forget()

        mode = self.main.configIDE.config("Board", "mode", "bootloader")
        getattr(self.radioButton_mode_bootloader, "select" if
                (mode == "bootloader") else "deselect")()
        getattr(self.radioButton_mode_icsp, "select" if
                (mode == "icsp") else "deselect")()

        bootloader = self.main.configIDE.config("Board", "bootloader", "v1_v2")
        getattr(self.radioButton_bootloader_v1_v2, "select" if
                (bootloader == "v1_v2") else "deselect")()
        getattr(self.radioButton_bootloader_v4, "select" if
                (bootloader == "v4") else "deselect")()

        self.update_mode()

    #----------------------------------------------------------------------
    def update_mode(self):

        mode_boot = self.mode_var.get() == "bootloader"
        arch_8 = self.arch_var.get() == 8

        if mode_boot and arch_8:
            self.lf_boot.pack(fill=X, expand=True, side=TOP)
        else:
            self.lf_boot.forget()
        self.init_groups()

        if not mode_boot:
            self.label_warning.configure(
                text="WARNING!! this mode can overwite the bootloader code.")
        else:
            self.label_warning.configure(text="")

    #----------------------------------------------------------------------
    def set_board_name(self, name, arch):
        def dummy():
            self.main.configIDE.set("Board", "board_" + arch, name)

        return dummy

    #----------------------------------------------------------------------
    def init_groups(self):

        self.lf_dev32.forget()
        self.lf_dev8.forget()

        if self.arch_var.get() == 8:
            self.lf_dev8.pack(fill=X, expand=True, side=TOP)
            self.advanceoptions.forget()

        else:
            self.lf_dev32.pack(fill=X, expand=True, side=TOP)
            self.advanceoptions.pack(fill=X, expand=True, side=BOTTOM)

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

        #if self.board_config.radioButton_arch_8.isChecked(): arch = 8
        #else: arch = 32
        self.main.configIDE.set("Board", "arch", self.arch_var.get())

        #if self.board_config.radioButton_mode_bootloader.isChecked(): mode = "bootloader"
        #else: mode = "icsp"
        self.main.configIDE.set("Board", "mode", self.mode_var.get())

        #if self.board_config.radioButton_bootloader_v1_v2.isChecked(): bootloader = "v1_v2"
        #else: bootloader = "v4"
        self.main.configIDE.set("Board", "bootloader", self.boot_var.get())

        name = self.main.configIDE.config("Board",
                                          "board_" + str(self.arch_var.get()),
                                          None)
        self.main.configIDE.set("Board", "board", name)

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

        self.save_config()
        self.main.configIDE.save_config()
        self.main.statusbar_ide(self.main.get_status_board())
        self.close_advance()
        self.quit()

    #----------------------------------------------------------------------
    def advance(self):

        root = Toplevel()
        self.frame_advance = BoardConfigAdvance(master=root, main=self.main)
        self.frame_advance.mainloop()

    #----------------------------------------------------------------------
    def close_advance(self):

        try:
            assert self.frame_advance
        except:
            return
        self.frame_advance.quit()
Example #25
0
class TreeNode:

    def __init__(self, canvas, parent, item, menuList = []):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = 0
        self.children = {}
        self.kidKeys = []
        self.x = self.y = None
        self.iconimages = {} # cache of PhotoImage instances for icons
        self.menuList = menuList
        self.menuVar = IntVar()
        self.menuVar.set(0)
        self._popupMenu = None
        self.image_id = None
        if self.menuList:
            if self.menuList[-1] == 'Separator':
                self.menuList = self.menuList[:-1]
            self._popupMenu = Menu(self.canvas, tearoff = 0)
            for i in range(len(self.menuList)):
                item = self.menuList[i]
                if item == 'Separator':
                    self._popupMenu.add_separator()
                else:
                    self._popupMenu.add_radiobutton(
                        label = item,
                        variable = self.menuVar,
                        value = i,
                        indicatoron = 0,
                        command = self.popupMenuCommand)
                    
    def destroy(self):
        for key in self.kidKeys:
            c = self.children[key]
            del self.children[key]
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        try:
            return self.iconimages[name]
        except KeyError:
            pass
        file, ext = os.path.splitext(name)
        ext = ext or ".gif"
        fullname = os.path.join(ICONDIR, file + ext)
        image = PhotoImage(master=self.canvas, file=fullname)
        self.iconimages[name] = image
        return image

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = 1
        if self.parent != None:
            if self.parent.state == 'expanded':
                self.canvas.delete(self.image_id)
                self.drawicon()
                self.drawtext()
        self.item.OnSelect(event)

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = 0
        if self.parent != None:
            if self.parent.state == 'expanded':
                self.canvas.delete(self.image_id)
                self.drawicon()
                self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for key in self.kidKeys:
            child = self.children[key]
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def popupMenu(self, event=None):
        if self._popupMenu:
            self._popupMenu.post(event.widget.winfo_pointerx(),
                                 event.widget.winfo_pointery())
            return "break"

    def popupMenuCommand(self):
        command = self.menuList[self.menuVar.get()]
        self.item.MenuCommand(command)
        if self.parent and (command != 'Update Explorer'):
            # Update parent to try to keep explorer up to date
            self.parent.update()

    def expand(self, event=None):
        if not self.item.IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y - 2
        bottom = self.lastvisiblechild().y + 17
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def reveal(self):
        # Make sure all parent nodes are marked as expanded
        parent = self.parent
        while parent:
            if parent.state == 'collapsed':
                parent.state = 'expanded'
                parent = parent.parent
            else:
                break
        # Redraw tree accordingly
        self.update()
        # Bring this item into view
        self.view()

    def lastvisiblechild(self):
        if self.kidKeys and self.state == 'expanded':
            return self.children[self.kidKeys[-1]].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(Tkinter.ALL)     # XXX could be more subtle
            self.draw(7, 2)
            x0, y0, x1, y1 = self.canvas.bbox(Tkinter.ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor

    def draw(self, x, y):
        # XXX This hard-codes too many geometry constants!
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y+17
        # draw children
        sublist = self.item._GetSubList()
        if not sublist:
            # IsExpandable() was mistaken; that's allowed
            return y+17
        self.kidKeys = []
        for item in sublist:
            key = item.GetKey()
            if self.children.has_key(key):
                child = self.children[key]
            else:
                child = TreeNode(self.canvas, self, item, self.menuList)
            self.children[key] = child
            self.kidKeys.append(key)
        # Remove unused children
        for key in self.children.keys():
            if key not in self.kidKeys:
                del(self.children[key])
        cx = x+20
        cy = y+17
        cylast = 0
        for key in self.kidKeys:
            child = self.children[key]
            cylast = cy
            self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")
            cy = child.draw(cx, cy)
            if child.item.IsExpandable():
                if child.state == 'expanded':
                    iconname = "minusnode"
                    callback = child.collapse
                else:
                    iconname = "plusnode"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x+9, cylast+7, image=image)
                # XXX This leaks bindings until canvas is deleted:
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,
            ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
            fill="gray50")
        self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2
        return cy

    def drawicon(self):
        if self.selected:
            imagename = (self.item.GetSelectedIconName() or
                         self.item.GetIconName() or
                         "openfolder")
        else:
            imagename = self.item.GetIconName() or "folder"
        image = self.geticonimage(imagename)
        id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
        self.image_id = id
        self.canvas.tag_bind(id, "<1>", self.select)
        self.canvas.tag_bind(id, "<Double-1>", self.flip)
        self.canvas.tag_bind(id, "<3>", self.popupMenu)
        
    def drawtext(self, text=None):
        textx = self.x+20-1
        texty = self.y-1
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx, texty, anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + 10
        if text==None:
            text = self.item.GetText() or "<no text>"
        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            label = self.label
        except AttributeError:
            # padding carefully selected (on Windows) to match Entry widget:
            self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
        if self.selected:
            self.label.configure(fg="white", bg="darkblue")
        else:
            fg = self.item.GetTextFg()
            self.label.configure(fg=fg, bg="white")
        id = self.canvas.create_window(textx, texty,
                                       anchor="nw", window=self.label)
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.label.bind("<3>", self.popupMenu)
        # Update text if necessary
        if text != self.label['text']:
            self.label['text'] = text
        self.text_id = id

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            text = self.item.GetTextForEdit()
            self.label['text'] = text
            self.drawtext(text)
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, Tkinter.END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        self.drawtext()
        self.canvas.focus_set()

    def find(self, searchKey):
        # Search for a node who's key matches the given key
        # Is it this node
        if searchKey == self.item.GetKey():
            return self
        # Nope, check the children
        sublist = self.item._GetSubList()
        for item in sublist:
            key = item.GetKey()
            # Use existing child or create new TreeNode if none exists
            if self.children.has_key(key):
                child = self.children[key]
            else:
                child = TreeNode(self.canvas, self, item, self.menuList)
                # Update local list of children and keys
                self.children[key] = child
                self.kidKeys.append(key)
            # See if node is child (or one of child's descendants)
            retVal = child.find(searchKey)
            if retVal:
                return retVal
        # Not here
        return None
Example #26
0
class TreeNode:
    def __init__(self, canvas, parent, item, menuList=[]):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = 0
        self.children = {}
        self.kidKeys = []
        self.x = self.y = None
        self.iconimages = {}  # cache of PhotoImage instances for icons
        self.menuList = menuList
        self.menuVar = IntVar()
        self.menuVar.set(0)
        self._popupMenu = None
        self.image_id = None
        if self.menuList:
            if self.menuList[-1] == 'Separator':
                self.menuList = self.menuList[:-1]
            self._popupMenu = Menu(self.canvas, tearoff=0)
            for i in range(len(self.menuList)):
                item = self.menuList[i]
                if item == 'Separator':
                    self._popupMenu.add_separator()
                else:
                    self._popupMenu.add_radiobutton(
                        label=item,
                        variable=self.menuVar,
                        value=i,
                        indicatoron=0,
                        command=self.popupMenuCommand)

    def destroy(self):
        for key in self.kidKeys:
            c = self.children[key]
            del self.children[key]
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        try:
            return self.iconimages[name]
        except KeyError:
            pass
        file, ext = os.path.splitext(name)
        ext = ext or ".gif"
        fullname = os.path.join(ICONDIR, file + ext)
        image = PhotoImage(master=self.canvas, file=fullname)
        self.iconimages[name] = image
        return image

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = 1
        if self.parent != None:
            if self.parent.state == 'expanded':
                self.canvas.delete(self.image_id)
                self.drawicon()
                self.drawtext()
        self.item.OnSelect(event)

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = 0
        if self.parent != None:
            if self.parent.state == 'expanded':
                self.canvas.delete(self.image_id)
                self.drawicon()
                self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for key in self.kidKeys:
            child = self.children[key]
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def popupMenu(self, event=None):
        if self._popupMenu:
            self._popupMenu.post(event.widget.winfo_pointerx(),
                                 event.widget.winfo_pointery())
            return "break"

    def popupMenuCommand(self):
        command = self.menuList[self.menuVar.get()]
        self.item.MenuCommand(command)
        if self.parent and (command != 'Update Explorer'):
            # Update parent to try to keep explorer up to date
            self.parent.update()

    def expand(self, event=None):
        if not self.item.IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y - 2
        bottom = self.lastvisiblechild().y + 17
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def reveal(self):
        # Make sure all parent nodes are marked as expanded
        parent = self.parent
        while parent:
            if parent.state == 'collapsed':
                parent.state = 'expanded'
                parent = parent.parent
            else:
                break
        # Redraw tree accordingly
        self.update()
        # Bring this item into view
        self.view()

    def lastvisiblechild(self):
        if self.kidKeys and self.state == 'expanded':
            return self.children[self.kidKeys[-1]].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(Tkinter.ALL)  # XXX could be more subtle
            self.draw(7, 2)
            x0, y0, x1, y1 = self.canvas.bbox(Tkinter.ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor

    def draw(self, x, y):
        # XXX This hard-codes too many geometry constants!
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y + 17
        # draw children
        sublist = self.item._GetSubList()
        if not sublist:
            # IsExpandable() was mistaken; that's allowed
            return y + 17
        self.kidKeys = []
        for item in sublist:
            key = item.GetKey()
            if self.children.has_key(key):
                child = self.children[key]
            else:
                child = TreeNode(self.canvas, self, item, self.menuList)
            self.children[key] = child
            self.kidKeys.append(key)
        # Remove unused children
        for key in self.children.keys():
            if key not in self.kidKeys:
                del (self.children[key])
        cx = x + 20
        cy = y + 17
        cylast = 0
        for key in self.kidKeys:
            child = self.children[key]
            cylast = cy
            self.canvas.create_line(x + 9, cy + 7, cx, cy + 7, fill="gray50")
            cy = child.draw(cx, cy)
            if child.item.IsExpandable():
                if child.state == 'expanded':
                    iconname = "minusnode"
                    callback = child.collapse
                else:
                    iconname = "plusnode"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x + 9, cylast + 7, image=image)
                # XXX This leaks bindings until canvas is deleted:
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(
            x + 9,
            y + 10,
            x + 9,
            cylast + 7,
            ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
            fill="gray50")
        self.canvas.tag_lower(id)  # XXX .lower(id) before Python 1.5.2
        return cy

    def drawicon(self):
        if self.selected:
            imagename = (self.item.GetSelectedIconName()
                         or self.item.GetIconName() or "openfolder")
        else:
            imagename = self.item.GetIconName() or "folder"
        image = self.geticonimage(imagename)
        id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
        self.image_id = id
        self.canvas.tag_bind(id, "<1>", self.select)
        self.canvas.tag_bind(id, "<Double-1>", self.flip)
        self.canvas.tag_bind(id, "<3>", self.popupMenu)

    def drawtext(self, text=None):
        textx = self.x + 20 - 1
        texty = self.y - 1
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx,
                                         texty,
                                         anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + 10
        if text == None:
            text = self.item.GetText() or "<no text>"
        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            label = self.label
        except AttributeError:
            # padding carefully selected (on Windows) to match Entry widget:
            self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
        if self.selected:
            self.label.configure(fg="white", bg="darkblue")
        else:
            fg = self.item.GetTextFg()
            self.label.configure(fg=fg, bg="white")
        id = self.canvas.create_window(textx,
                                       texty,
                                       anchor="nw",
                                       window=self.label)
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.label.bind("<3>", self.popupMenu)
        # Update text if necessary
        if text != self.label['text']:
            self.label['text'] = text
        self.text_id = id

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            text = self.item.GetTextForEdit()
            self.label['text'] = text
            self.drawtext(text)
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, Tkinter.END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        self.drawtext()
        self.canvas.focus_set()

    def find(self, searchKey):
        # Search for a node who's key matches the given key
        # Is it this node
        if searchKey == self.item.GetKey():
            return self
        # Nope, check the children
        sublist = self.item._GetSubList()
        for item in sublist:
            key = item.GetKey()
            # Use existing child or create new TreeNode if none exists
            if self.children.has_key(key):
                child = self.children[key]
            else:
                child = TreeNode(self.canvas, self, item, self.menuList)
                # Update local list of children and keys
                self.children[key] = child
                self.kidKeys.append(key)
            # See if node is child (or one of child's descendants)
            retVal = child.find(searchKey)
            if retVal:
                return retVal
        # Not here
        return None
Example #27
0
    def modifica_contacte(self):
        if self.child_toplevel is not None:
            self.child_toplevel.destroy()

        element_a_modificar = self.agenda_contactes.focus()
        valor_usuari = self.agenda_contactes.item(
            element_a_modificar)['values']
        self.cursor.execute("select * from CONTACTES where nom=? and telf=?;",
                            tuple(valor_usuari))
        dades = self.cursor.fetchone()
        t = Toplevel()
        self.child_toplevel = t

        label_imatge = Label(t)
        label_imatge.configure(background='white')
        label_imatge.pack(side="left", fill="both", expand=True)
        self.show_image(label_imatge, dades[3])
        frame_info = Frame(t)
        frame_info.pack(side="right", fill="both", expand=False)
        frame_info.configure(background='white')
        label_nom = Label(frame_info, text="Nom: ")
        label_nom.configure(background='white')
        label_nom.grid(row=0, column=0)
        entry_nom = Entry(frame_info,
                          textvariable=StringVar(frame_info, value=dades[0]),
                          width=20,
                          state='disabled')
        entry_nom.grid(row=0, column=1)
        label_telefon = Label(frame_info, text="Telefon antic: ")
        label_telefon.configure(background='white')
        label_telefon.grid(row=1, column=0)
        text_telefon = StringVar(frame_info, value=dades[1])
        entry_telefon = Entry(frame_info,
                              textvariable=text_telefon,
                              width=20,
                              state='disabled')
        entry_telefon.grid(row=1, column=1)

        label_telefon_nou = Label(frame_info, text="Telefon nou: ")
        label_telefon_nou.configure(background='white')
        label_telefon_nou.grid(row=2, column=0)
        entry_telefon_nou = Entry(frame_info, width=20)
        entry_telefon_nou.grid(row=2, column=1)

        label_email = Label(frame_info, text="Email: ")
        label_email.configure(background='white')
        label_email.grid(row=3, column=0)
        text_email = StringVar(frame_info, value=dades[2])  #-----
        entry_email = Entry(frame_info,
                            width=20,
                            textvariable=text_email,
                            state='disabled')
        entry_email.grid(row=3, column=1)
        label_email_nou = Label(frame_info, text="Email nou:")
        label_email_nou.configure(background='white')
        label_email_nou.grid(row=4, column=0)
        entry_email_nou = Entry(frame_info, width=20)
        entry_email_nou.grid(row=4, column=1)

        selecciona_imatge = Button(
            frame_info,
            text="Edita foto",
            command=lambda: self.demana_imatge(label_imatge, dades[0],
                                               text_telefon.get()))
        selecciona_imatge.grid(row=5)
        button_modifica_contacte = Button(
            frame_info,
            text="Modificar contacte",
            fg="Blue",
            command=lambda: self.modificar_contacte([
                entry_nom, entry_telefon, entry_email, text_telefon, text_email
            ], [entry_telefon_nou, entry_email_nou], element_a_modificar))
        button_modifica_contacte.grid(row=6, column=1, sticky=E)
Example #28
0
File: qgui.py Project: jkpr/QTools2
class PmaConvert:
    def __init__(self, config):
        root = Tk()

        # Root Definition
        root.geometry('1100x700')
        root.title('PMA Convert')

        # Configuration and Variables
        self.file_selection = ''
        self.is_converting = False
        self.options = config['option_definitions']
        gui_config = config['gui_config']

        # UI
        ## Frames
        self.main_frame = Frame(root)
        self.position_main_frame(gui_config['screen_orientation'])

        ## Components
        self.log = Text(self.main_frame, bd=1, relief=SUNKEN, width=140,
                        height=23, state=DISABLED, spacing3=1, wrap=WORD)

        choose_text = ('1. Choose XLSForm (.xls or .xlsx) file(s) for '
                       'conversion.')
        self.choose_files_label = Label(self.main_frame, text=choose_text)
        # TODO: Get spacing to work.
        # self.choose_files_label.grid(row=3, column=3, padx=(50, 50))
        # self.choose_files_label.grid(row=3, column=3, pady=(50, 50))
        self.choose_files_label.pack()
        self.choose_files_button = Button(self.main_frame,
                                          text='Choose file...', fg='black',
                                          command=self.on_open)
        self.choose_files_button.pack()

        out_text = 'Choose location for output file(s).'
        self.output_location_label = Label(self.main_frame, text=out_text)
        self.output_location_button = Button(self.main_frame,
                                             text='Choose location...',
                                             fg='black')
        if gui_config['output_location_on'] is True:
            self.output_location_label.pack()
            self.output_location_button.pack()

        self.choose_options_label = Label(self.main_frame,
                                          text='2. Choose conversion options.')
        self.choose_options_label.pack()

        ### Create Options Checkboxes
        # Task: Dynamically generate: http://stackoverflow.com/questions/...
        # ...553784/can-you-use-a-string-to-instantiate-a-class-in-python
        self.preexisting = BooleanVar()
        pre_text = self.options['preexisting']['label']
        self.preexisting_opt = Checkbutton(self.main_frame, text=pre_text,
                                           variable=self.preexisting)
        self.preexisting_opt.pack()
        self.regular = BooleanVar()
        reg_text = self.options['regular']['label']
        self.regular_opt = Checkbutton(self.main_frame, text=reg_text,
                                       variable=self.regular)
        self.regular_opt.pack()
        self.novalidate = BooleanVar()
        noval_text = self.options['novalidate']['label']
        self.novalidate_opt = Checkbutton(self.main_frame, text=noval_text,
                                          variable=self.novalidate)
        self.novalidate_opt.pack()
        self.ignore_version = BooleanVar()
        ig_text = self.options['ignore_version']['label']
        self.ignore_version_opt = Checkbutton(self.main_frame, text=ig_text,
                                              variable=self.ignore_version)
        self.ignore_version_opt.pack()
        self.linking_warn = BooleanVar()
        link_text = self.options['linking_warn']['label']
        self.linking_warn_option = Checkbutton(self.main_frame, text=link_text,
                                               variable=self.linking_warn)
        self.linking_warn_option.pack()
        self.debug = BooleanVar()
        debug_text = self.options['debug']['label']
        self.debug_option = Checkbutton(self.main_frame, text=debug_text,
                                        variable=self.debug)
        self.debug_option.pack()
        self.extras = BooleanVar()
        extras_text = self.options['extras']['label']
        self.extras_option = Checkbutton(self.main_frame, text=extras_text,
                                         variable=self.extras)
        self.extras_option.pack()

        self.convert_label = Label(self.main_frame, text='3. Run conversion.')
        self.convert_label.pack()

        # Task: Add xscrollcommand and yscrollcommand.
        self.convert_button = Button(self.main_frame, text='Convert',
                                     fg='black', command=self.convert)
        self.convert_button.pack()
        self.log.pack(fill=X, expand=1)
        self.log_text('PMA Convert allows you to convert .xls or .xlsx form '
                      'definition files to files which are compatible with ODK '
                      'Collect.\n\nIf you need to copy and paste from this '
                      'log, highlight the text and press CTRL+C to copy. Then '
                      'press CTRL+V to paste.\n\n'
                      '====================================================\n\n'
                      'Awaiting file selection.')

        # Task: Fix menus. They're not working.
        self.context_menu = Menu(self.main_frame, tearoff=0)
        self.context_menu.add_command(label="Convert", command=self.convert)
        self.main_frame.bind("<Button-3>", self.popup)

        # - Note: Strangely this stopped anchoring to bottom suddenly, for some
        # reason. So it is temporarily disabled.
        self.status_bar = Label(self.main_frame,
                                text='Awaiting file selection.',
                                bd=1, relief=SUNKEN, anchor=W)
        if gui_config['status_bar_on'] is True:
            self.status_bar.pack(side=BOTTOM, fill=X)

        # Run
        root.mainloop()

    # Functions
    def popup(self, event):
        # Note: Currently doesn't work.
        self.context_menu.post(event.x_root, event.y_root)
        # display the popup menu
        try:
            self.context_menu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            # make sure to release the grab (Tk 8.0a1 only)
            self.context_menu.grab_release()

    def position_main_frame(self, orientation):
        if orientation == 'center':
            x, y, a = .5, .5, 'c'
            return self.main_frame.place(relx=x, rely=y, anchor=a)
        elif orientation == 'top':
            return self.main_frame.pack()
        else:
            return self.main_frame.pack()

    def on_open(self):
        file_types = [
            ('XLS Files', '*.xls'),
            ('XLSX Files', '*.xlsx'),
            ('All files', '*')
        ]
        try:
            self.file_selection = tkFileDialog.askopenfilename(
                filetypes=file_types, title='Open one or more files.',
                message='Open one or more files', multiple=1
            )
        except:
            self.file_selection = tkFileDialog.askopenfilename(
                filetypes=file_types, title='Open one or more files.', multiple=1
            )
        if self.file_selection != '':
            self.set_status('Click on Convert to convert files.')
            log_output = 'Ready for conversion: \n'
            for file in self.file_selection:
                log_output += '* ' + str(file) + '\n'
            log_output = log_output[:-1] # Removes the last '\n'.
            self.log.configure(self.log_text(log_output))

    def set_status(self, new_status):
        self.status_bar.configure(text=new_status)

    def log_text(self, new_text):
        self.log.configure(state=NORMAL)
        self.log.insert(END, str(new_text) + '\n\n')
        self.log.configure(state=DISABLED)
        self.log.bind("<1>", lambda event: self.log.focus_set())

    def convert(self):
        if self.file_selection != '':
            f = self.file_selection

            kwargs = {
                SUFFIX: u'',
                PREEXISTING: self.preexisting.get(),
                PMA: not self.regular.get(),
                CHECK_VERSIONING: not self.ignore_version.get(),
                STRICT_LINKING: not self.linking_warn.get(),
                VALIDATE: not self.novalidate.get(),
                EXTRAS: self.extras.get(),
                DEBUG: self.debug.get()
            }

            buffer = StringIO.StringIO()
            if not kwargs[DEBUG]:
                sys.stdout = buffer
                sys.stderr = buffer
            else:
                self.log_text('--> DEBUG MODE: check console output')

            try:
                xlsform_convert(f, **kwargs)
            except ConvertError as e:
                print unicode(e)
            except OSError as e:
                # Should catch WindowsError, impossible to test on Mac
                traceback.print_exc()
                print e

            if not kwargs[DEBUG]:
                sys.stdout = sys.__stdout__
                sys.stderr = sys.__stderr__

            self.log_text(buffer.getvalue())
class WindowExample(Frame):

	def __init__(self, parent):
		Frame.__init__(self, parent)
		self.result = 0
		self.master.title("This is a test")
		self.master.minsize(width = 600, height = 800)
		#self.master.


		self.prompt = Label(self, text = "Enter a number:", anchor = "w", fg = "#984301")
		self.entry  = Entry(self, width = 50, highlightcolor = "red")
		self.submit = Button(self, text = "Submit", command = self.calculate)
		self.exit   = Button(self, text = "Exit", command = parent.destroy, fg = "red")
		self.output = Label(self, text = "")
		self.menu   = Menu(self, title = "Menu test", bg = "black")
		self.canvas = Canvas(self, cursor = "circle", highlightcolor = "blue", bg = "#019bf0")

		self.button1 = Button(self, text = "tast antum", bg = "red", fg = "green", command = self.newWindow, \
								activebackground = "red", activeforeground = "blue", relief = "sunken", cursor = "dot")

		self.newFrame = Frame(self, bg = "green", highlightcolor = "blue")
		self.button2 = Button(self.newFrame, text = "This is a tast")
		self.button2.grid()
		self.scale = Scale(self, from_ = 50, to_ = 60, orient = "horizontal", digits = 3, resolution = 0.25, highlightcolor = "red", command = self.calculate)
		self.scale.pack()
		self.open_file_button = Button(self, text = "Open File", command = self.openFile)

		self.prompt.pack(side = "top", fill = "x")
		self.entry.pack(side = "top", fill = "x")
		self.output.pack(side = "top", fill = "x", expand = True)
		self.submit.pack(side = "right")
		self.exit.pack(side = "left")
		self.button1.pack(fill="x")
		self.newFrame.pack(side="bottom", fill = "x", expand = True)
		self.button2.grid()
		self.canvas.pack()
		self.open_file_button.pack()
		#self.slider.pack()

		#self.tk = Tkinter.Tk()
		#self.tk.withdrow()
		#self.file_path = Tkinter.filedialog.askopenfilename()
		#print("test")
		self.entry.insert(string = "3", index = 0)
		#self.entry.insert(string = "blahblah", index = 3)

	def calculate(self, integer):
		integer = float(integer)
		#try:
		#	i = int(self.entry.get())
		#	self.result = "%s*2=%s" % (i, i*2)
		#except ValueError:
		#	self.result = "Please enter numbers only"
		self.entry.delete(0, len(self.entry.get()))
		self.result = "%s*2=%s" % (integer, integer*2)
		self.entry.insert(0, integer)

		self.output.configure(text=self.result)

	def newWindow(self):
		try:
			r2 = Tk()
			r2.mainloop()
		except ValueError:
			return None

	def openFile(self):
		file_in = tkFileDialog.askopenfilename()
		self.output.configure(text = file_in)
Example #30
0
class TreeNode:
    def __init__(self, canvas, parent, item):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = False
        self.children = []
        self.x = self.y = None
        self.iconimages = {}  # cache of PhotoImage instances for icons

    def destroy(self):
        for c in self.children[:]:
            self.children.remove(c)
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        try:
            return self.iconimages[name]
        except KeyError:
            pass
        file, ext = os.path.splitext(name)
        ext = ext or ".gif"
        fullname = os.path.join(ICONDIR, file + ext)
        image = PhotoImage(master=self.canvas, file=fullname)
        self.iconimages[name] = image
        return image

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = True
        self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = False
        self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for child in self.children:
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def expand(self, event=None):
        if not self.item._IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y - 2
        bottom = self.lastvisiblechild().y + 17
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def lastvisiblechild(self):
        if self.children and self.state == 'expanded':
            return self.children[-1].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(ALL)  # XXX could be more subtle
            self.draw(7, 2)
            x0, y0, x1, y1 = self.canvas.bbox(ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor

    def draw(self, x, y):
        # XXX This hard-codes too many geometry constants!
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y + 17
        # draw children
        if not self.children:
            sublist = self.item._GetSubList()
            if not sublist:
                # _IsExpandable() was mistaken; that's allowed
                return y + 17
            for item in sublist:
                child = self.__class__(self.canvas, self, item)
                self.children.append(child)
        cx = x + 20
        cy = y + 17
        cylast = 0
        for child in self.children:
            cylast = cy
            self.canvas.create_line(x + 9, cy + 7, cx, cy + 7, fill="gray50")
            cy = child.draw(cx, cy)
            if child.item._IsExpandable():
                if child.state == 'expanded':
                    iconname = "minusnode"
                    callback = child.collapse
                else:
                    iconname = "plusnode"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x + 9, cylast + 7, image=image)
                # XXX This leaks bindings until canvas is deleted:
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(
            x + 9,
            y + 10,
            x + 9,
            cylast + 7,
            ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
            fill="gray50")
        self.canvas.tag_lower(id)  # XXX .lower(id) before Python 1.5.2
        return cy

    def drawicon(self):
        if self.selected:
            imagename = (self.item.GetSelectedIconName()
                         or self.item.GetIconName() or "openfolder")
        else:
            imagename = self.item.GetIconName() or "folder"
        image = self.geticonimage(imagename)
        id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
        self.image_id = id
        self.canvas.tag_bind(id, "<1>", self.select)
        self.canvas.tag_bind(id, "<Double-1>", self.flip)

    def drawtext(self):
        textx = self.x + 20 - 1
        texty = self.y - 1
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx,
                                         texty,
                                         anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + 10
        text = self.item.GetText() or "<no text>"
        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            label = self.label
        except AttributeError:
            # padding carefully selected (on Windows) to match Entry widget:
            self.label = Label(self.canvas, text=text)
            if not TTK:
                self.label.configure(bd=0, padx=2, pady=2)
        theme = idleConf.GetOption('main', 'Theme', 'name')
        if self.selected:
            self.label.configure(idleConf.GetHighlight(theme, 'hilite'))
        else:
            self.label.configure(idleConf.GetHighlight(theme, 'normal'))
        id = self.canvas.create_window(textx,
                                       texty,
                                       anchor="nw",
                                       window=self.label)
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.text_id = id

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        entry.destroy()
        self.drawtext()
        self.canvas.focus_set()
Example #31
0
class GUI:
    def __init__(self, model, title='PyCX Simulator', interval=0, stepSize=1,
            param_gui_names=None):
        self.model = model
        self.titleText = title
        self.timeInterval = interval
        self.stepSize = stepSize
        self.param_gui_names = param_gui_names
        if param_gui_names is None:
            self.param_gui_names = {}
        self.param_entries = {}
        self.statusStr = ""
        self.running = False
        self.modelFigure = None
        self.currentStep = 0

        self.initGUI()

    def initGUI(self):
        #create root window
        self.rootWindow = Tk()
        self.statusText = StringVar(value=self.statusStr)
        self.setStatusStr("Simulation not yet started")

        self.rootWindow.wm_title(self.titleText)
        self.rootWindow.protocol('WM_DELETE_WINDOW', self.quitGUI)
        self.rootWindow.geometry('550x700')
        self.rootWindow.columnconfigure(0, weight=1)
        self.rootWindow.rowconfigure(0, weight=1)

        self.frameSim = Frame(self.rootWindow)

        self.frameSim.pack(expand=YES, fill=BOTH, padx=5, pady=5, side=TOP)
        self.status = Label(self.rootWindow, width=40, height=3, relief=SUNKEN,
                            bd=1, textvariable=self.statusText)
        self.status.pack(side=TOP, fill=X, padx=1, pady=1, expand=NO)

        self.runPauseString = StringVar()
        self.runPauseString.set("Run")
        self.buttonRun = Button(self.frameSim, width=30, height=2,
                                textvariable=self.runPauseString,
                                command=self.runEvent)
        self.buttonRun.pack(side=TOP, padx=5, pady=5)

        self.showHelp(self.buttonRun,
                      "Runs the simulation (or pauses the running simulation)")
        self.buttonStep = Button(self.frameSim, width=30, height=2,
                                 text="Step Once", command=self.stepOnce)
        self.buttonStep.pack(side=TOP, padx=5, pady=5)
        self.showHelp(self.buttonStep, "Steps the simulation only once")
        self.buttonReset = Button(self.frameSim, width=30, height=2,
                                  text="Reset", command=self.resetModel)
        self.buttonReset.pack(side=TOP, padx=5, pady=5)
        self.showHelp(self.buttonReset, "Resets the simulation")

        for param in self.model.params:
            var_text = self.param_gui_names.get(param, param)
            can = Canvas(self.frameSim)
            lab = Label(can, width=25, height=1 + var_text.count('\n'),
                        text=var_text, anchor=W, takefocus=0)
            lab.pack(side='left')
            ent = Entry(can, width=11)
            val = getattr(self.model, param)
            if isinstance(val, bool):
                val = int(val)  # Show 0/1 which can convert back to bool
            ent.insert(0, str(val))
            ent.pack(side='left')
            can.pack(side='top')
            self.param_entries[param] = ent
        if self.param_entries:
            self.buttonSaveParameters = Button(self.frameSim, width=50,
                    height=1, command=self.saveParametersCmd,
                    text="Save parameters to the running model", state=DISABLED)
            self.showHelp(self.buttonSaveParameters,
                    "Saves the parameter values.\n" +
                    "Not all values may take effect on a running model\n" +
                    "A model reset might be required.")
            self.buttonSaveParameters.pack(side='top', padx=5, pady=5)
            self.buttonSaveParametersAndReset = Button(self.frameSim, width=50,
                    height=1, command=self.saveParametersAndResetCmd,
                    text="Save parameters to the model and reset the model")
            self.showHelp(self.buttonSaveParametersAndReset,
                    "Saves the given parameter values and resets the model")
            self.buttonSaveParametersAndReset.pack(side='top', padx=5, pady=5)

        can = Canvas(self.frameSim)
        lab = Label(can, width=25, height=1, text="Step size ", justify=LEFT,
                anchor=W, takefocus=0)
        lab.pack(side='left')
        self.stepScale = Scale(can, from_=1, to=500, resolution=1,
                               command=self.changeStepSize, orient=HORIZONTAL,
                               width=25, length=150)
        self.stepScale.set(self.stepSize)
        self.showHelp(self.stepScale,
                "Skips model redraw during every [n] simulation steps\n" +
                "Results in a faster model run.")
        self.stepScale.pack(side='left')
        can.pack(side='top')

        can = Canvas(self.frameSim)
        lab = Label(can, width=25, height=1,
                    text="Step visualization delay in ms ", justify=LEFT,
                    anchor=W, takefocus=0)
        lab.pack(side='left')
        self.stepDelay = Scale(can, from_=0, to=max(2000, self.timeInterval),
                               resolution=10, command=self.changeStepDelay,
                               orient=HORIZONTAL, width=25, length=150)
        self.stepDelay.set(self.timeInterval)
        self.showHelp(self.stepDelay, "The visualization of each step is " +
                                      "delays by the given number of " +
                                      "milliseconds.")
        self.stepDelay.pack(side='left')
        can.pack(side='top')

    def setStatusStr(self, newStatus):
        self.statusStr = newStatus
        self.statusText.set(self.statusStr)

    #model control functions
    def changeStepSize(self, val):
        self.stepSize = int(val)

    def changeStepDelay(self, val):
        self.timeInterval = int(val)

    def saveParametersCmd(self):
        for param, entry in self.param_entries.items():
            val = entry.get()
            if isinstance(getattr(self.model, param), bool):
                val = bool(int(val))
            setattr(self.model, param, val)
            # See if the model changed the value (e.g. clipping)
            new_val = getattr(self.model, param)
            if isinstance(new_val, bool):
                new_val = int(new_val)
            entry.delete(0, END)
            entry.insert(0, str(new_val))
        self.setStatusStr("New parameter values have been set")

    def saveParametersAndResetCmd(self):
        self.saveParametersCmd()
        self.resetModel()

    def runEvent(self):
        if not self.running:
            self.running = True
            self.rootWindow.after(self.timeInterval, self.stepModel)
            self.runPauseString.set("Pause")
            self.buttonStep.configure(state=DISABLED)
            if self.param_entries:
                self.buttonSaveParameters.configure(state=NORMAL)
                self.buttonSaveParametersAndReset.configure(state=DISABLED)
        else:
            self.stopRunning()

    def stopRunning(self):
        self.running = False
        self.runPauseString.set("Continue Run")
        self.buttonStep.configure(state=NORMAL)
        self.drawModel()
        if self.param_entries:
            self.buttonSaveParameters.configure(state=NORMAL)
            self.buttonSaveParametersAndReset.configure(state=NORMAL)

    def stepModel(self):
        if self.running:
            if self.model.step() is True:
                self.stopRunning()
            self.currentStep += 1
            self.setStatusStr("Step " + str(self.currentStep))
            self.status.configure(foreground='black')
            if (self.currentStep) % self.stepSize == 0:
                self.drawModel()
            self.rootWindow.after(int(self.timeInterval * 1.0 / self.stepSize),
                                  self.stepModel)

    def stepOnce(self):
        self.running = False
        self.runPauseString.set("Continue Run")
        self.model.step()
        self.currentStep += 1
        self.setStatusStr("Step " + str(self.currentStep))
        self.drawModel()
        if self.param_entries:
            self.buttonSaveParameters.configure(state=NORMAL)

    def resetModel(self):
        self.running = False
        self.runPauseString.set("Run")
        self.model.reset()
        self.currentStep = 0
        self.setStatusStr("Model has been reset")
        self.drawModel()

    def drawModel(self):
        if self.modelFigure is None:
            self.modelFigure = plt.figure()
            plt.ion()
        self.model.draw()

        # Tell matplotlib to redraw too. The darwin-version works with more
        # types of matplotlib backends, but seems to fail on some Linux
        # machines. Hence we use the TkAgg specific method when available.
        if sys.platform == 'darwin':
            self.modelFigure.canvas.manager.show()
        else:
            self.modelFigure.canvas.manager.window.update()

    def start(self):
        if self.model.step.__doc__:
            self.showHelp(self.buttonStep, self.model.step.__doc__.strip())

        self.model.reset()
        self.drawModel()
        self.rootWindow.mainloop()

    def quitGUI(self):
        plt.close('all')
        self.rootWindow.quit()
        self.rootWindow.destroy()

    def showHelp(self, widget, text):
        def setText(self):
            self.statusText.set(text)
            self.status.configure(foreground='blue')

        def showHelpLeave(self):
            self.statusText.set(self.statusStr)
            self.status.configure(foreground='black')
        widget.bind("<Enter>", lambda e: setText(self))
        widget.bind("<Leave>", lambda e: showHelpLeave(self))
Example #32
0
class TilePicker(Frame):
    def __init__(self, parent, doc, **kw):
        apply(Frame.__init__, (self, parent), kw)
        self.doc = doc
        self.tilePicker = None
        self.attrPicker = None
        self.status = None
        self.curTile = 0
        self.setAttribute(0)
        self.tilePicker = Label(self, image=self.tilePickerPI,
                                width=128, borderwidth=0)
        self.tilePicker.grid(row=0,column=0)
        self.tilePicker.bind("<Button-1>", self.tilePickerCallback)
        self.attrPicker = Label(self, image=self.attrPickerPI,
                                borderwidth=0)
        self.attrPicker.grid(row=1,column=0)
        self.attrPicker.bind("<Button-1>", self.attrPickerCallback)
        self.status = Label(self)
        self.status.grid(row=2,column=0)
        self.setStatus()

    def setAttribute(self, value):
        self.curAttribute = value & 0x03
        self.updateWidgets()

    def updateWidgets(self):
        self.tilePickerImage = renderChrFile(self.doc.chrdata,
                                             self.doc.clut,
                                             self.curAttribute * 4)
        self.tilePickerPI = ImageTk.PhotoImage(self.tilePickerImage)
        if self.tilePicker is not None:
            self.tilePicker.configure(image=self.tilePickerPI)

        previewTile = self.doc.renderTile(self.curTile, self.curAttribute)
        self.attrPickerImage = renderAttrPicker(previewTile,
                                                self.doc.clut,
                                                self.curAttribute)
        self.attrPickerPI = ImageTk.PhotoImage(self.attrPickerImage)
        if self.attrPicker is not None:
            self.attrPicker.configure(image=self.attrPickerPI)
        
        self.setStatus()

    def setTile(self, tile):
        self.curTile = tile
        self.setAttribute(self.curAttribute)

    def setStatus(self):
        if self.status is None:
            return
        label = "tile $%02x attr %d" % (self.curTile, self.curAttribute)
        self.status.configure(text=label)

    def tilePickerCallback(self, event):
        if event.x >= 0 and event.x < 128 and event.y >= 0 and event.y < 128:
            tileX = event.x // 8
            tileY = event.y // 8
            newTileNo = tileY * 16 + tileX
            #print "mouse was clicked on tile", newTileNo
            self.setTile(newTileNo)
            return
        print "mouse was clicked at (%d, %d)" % (event.x, event.y)

    def attrPickerCallback(self, event):
        if event.x >= 0 and event.x < 128:
            attr = event.x // 32
            #print "mouse was clicked on attribute", attr
            self.setAttribute(attr)
            return
        print "mouse was clicked at (%d, %d)" % (event.x, event.y)
Example #33
0
class ImagePicker(Frame):
    """
    A custom widget that allows for the selection and preview of a picture
    Note that in the current format, the image picker is specific to the
    maze builder project
    """
    def __init__(self, parent, label, default="No File Selected", auto_move=False, move_fold=None):
        """
        Construct the image picker instance

        :param default:     Use to set the image path and inital data loaded
        :param auto_move:   If this is set to true, the image picker will automatically
                            move the image into a defined relative folder in the same
                            relative location
        """
        Frame.__init__(self, parent)
        self._image_ref = None
        self._file_name = default if not default == "No File Selected" else None
        self._file_path = self._file_name
        self._parent = parent

        self._auto_move = auto_move
        if auto_move is True:
            self._folder = "/" + move_fold + "/"

        # Text label
        self._label = Label(self, text=label, anchor=W)
        self._label.grid(row=0, column=0, sticky=W, padx=2)
        self._label.config(width=10)

        # The label that displays the name of the selected file
        self._img_label = Label(self, text=default)
        self._img_label.config(width=15)
        self._img_label.grid(row=0, column=1, sticky=W)

        # Button that enables the previewing of the loaded picture
        self._pButton = Button(self, text="Preview", command=self._display_img, padx=5)
        self._pButton.config(width=8)
        self._pButton.grid(row=0, column=3, sticky=W)

        # Button that enables the loading of files
        self._fButton = Button(self, text="|...|", command=self._load_img_label, padx=5)
        self._fButton.config(width=4)
        self._fButton.grid(row=0, column=2)

    def _display_img(self):
        """
        Display a loaded image in a dialog
        """
        if self._file_path is None:
            Debug.printi("No picture has been loaded to preview", Debug.Level.ERROR)
            return
        photo = self._open_img(self._file_path)
        ImageViewDialog(self._parent, self._file_name, photo)


    def _open_img(self, img_name):
        """
        Open an image from its location on disk

        Retrieves an image in ImageTk form from a given file path
        and loads it for application use

        :img_name: The path/name (?) of the image to open
        """
        try:
            img = Image.open(img_name)
            photo = ImageTk.PhotoImage(img)
            return photo
        except IOError:
            Debug.printi("Unable to find image " + img_name, Debug.Level.ERROR)

    def _launch_file_b(self):
        """
        Launch a file selector dialog
        """
        types = [
            ("JPG", "*.jpg"),
            ("Bitmap", "*.bmp"),
            ("PNG", "*.png"),
            ("GIF", "*.gif"),
            ("All files", "*")]
        dialog = tkFileDialog.Open(self, filetypes = types)
        self._file_path = dialog.show()

        self._file_name = self._scrub_name(self._file_path)
        self._move_img()
        return self._file_name

    def _move_img(self):
        if self._auto_move is False:
            return
        # Else, move the image to the given folder that is in the same dir as this module
        try:
            src = self._file_path
            dest = os.path.dirname(os.path.realpath(__file__)) +"/" + self._file_name
            shutil.copy(src, dest)
            Debug.printi("Moving file " + self._file_path + " to location "
                         + os.path.dirname(os.path.realpath(__file__))
                         + self._file_name, Debug.Level.INFO)
        # eg. src and dest are the same file
        except shutil.Error as e:
            print('Error: %s' % e + " " +dest)
        # eg. source or destination doesn't exist
        except IOError as e:
            print('Error: %s' % e.strerror +" "+ dest)

    def _scrub_name(self, file_path):
        """
        Override: Parse and clean the filename
        """
        split = self._file_path.split("/")
        if self._auto_move is True:
            f_name = self._folder[1:] + split[-1]
        else:
            f_name = split[-1]
        return f_name

    def _load_img_label(self):
        """
        Changes the text in the widget label to the (adjusted) filepath of the image
        """
        name = self._launch_file_b()
        self._img_label.configure(text=name)

    def get(self):
        return self._file_name

    def set(self, val):
        self._file_name = val
        self._img_label.config(text=val)
Example #34
0
class NGA_Window_Config(Frame):

    com = None
    sys = None

    def __init__(self, parent, sys):
        Frame.__init__(self, parent)

        self.sys = sys
        self.sys.c_config_window = self

        self.parent = parent

        # get window configurations
        self.parent.geometry(self.sys.win_cfg.wConfig)
        self.parent.title(self.sys.win_cfg.sConfig)

        # draw window
        self.initUI()

        # window defaults

    def initUI(self):

        self.style = Style().configure("TFrame",
                                       background=self.sys.win_cfg.cBackground)
        self.pack(fill=BOTH, expand=1)

        # setup labels
        self.Embedded = Label(self,
                              width=15,
                              background=self.sys.win_cfg.cUnknown,
                              text="LED: COM0")
        self.Embedded.place(x=15, y=35)
        self.Stage = Label(self,
                           width=15,
                           background=self.sys.win_cfg.cUnknown,
                           text="Stages: COM0")
        self.Stage.place(x=15, y=60)

        # setup buttons
        configComButton = Button(self,
                                 text="COM Port Setup",
                                 command=self.com_port_search,
                                 width=17)
        configComButton.place(x=15, y=5)

        # close buttons
        closeButton = Button(self,
                             text="Close",
                             command=self.close_window,
                             width=17)
        closeButton.place(x=15, y=90)

    def close_window(self):
        self.parent.destroy()

    def com_port_search(self):
        self.Embedded.configure(text="LED: Searching ...")
        self.Stage.configure(text="Stages: Searching ...")

        # close stages because we are going to look at all ports
        self.sys.hw.clear_stage()
        self.sys.hw.clear_led()

        self.Embedded.configure(background=self.sys.win_cfg.cBad)
        self.Stage.configure(background=self.sys.win_cfg.cBad)
        self.parent.update()
        self.com = NGA_Config_Serial_Scan()
        self.update_connections()

    def update_connections(self):
        self.Embedded.configure(text="LED: " + self.com.serial_arduino)
        if (self.com.serial_arduino != "COM0"):
            self.Embedded.configure(background=self.sys.win_cfg.cGood)
        else:
            self.Stage.configure(text="LED: NOT FOUND")
            self.Embedded.configure(background=self.sys.win_cfg.cBad)

        if self.com.stage == "mmc100":
            self.Stage.configure(text="Stages: MMC: " + self.com.serial_MMC100)
            self.Stage.configure(background=self.sys.win_cfg.cGood)
        elif self.com.stage == "mfc2000":
            self.Stage.configure(text="Stages: MFC: " +
                                 self.com.serial_MFC2000)
            self.Stage.configure(background=self.sys.win_cfg.cGood)
        elif self.com.stage == "smc-pollux":
            self.Stage.configure(text="Stages: SMC: " +
                                 self.com.serial_SMCPOLLUX)
            self.Stage.configure(background=self.sys.win_cfg.cGood)
        elif self.com.stage == "mmc_pollux_hybrid":
            self.Stage.configure(text=self.com.serial_MMC100 + "/" +
                                 self.com.serial_SMCPOLLUX)
            self.Stage.configure(background=self.sys.win_cfg.cGood)
        elif self.com.stage == "mfc_pollux_hybrid":
            self.Stage.configure(text=self.com.serial_MFC2000 + "/" +
                                 self.com.serial_SMCPOLLUX)
            self.Stage.configure(background=self.sys.win_cfg.cGood)
        else:
            self.Stage.configure(text="Stages: NOT FOUND")
            self.Stage.configure(background=self.sys.win_cfg.cBad)

        # reload stages because port may have changed
        self.sys.c_main_window.reload_leds()
        self.sys.c_main_window.reload_stages()
Example #35
0
class Chatbox(object):
    def __init__(self,
                 master,
                 my_nick=None,
                 command=None,
                 topic=None,
                 entry_controls=None,
                 maximum_lines=None,
                 timestamp_template=None,
                 scrollbar_background=None,
                 scrollbar_troughcolor=None,
                 history_background=None,
                 history_font=None,
                 history_padx=None,
                 history_pady=None,
                 history_width=None,
                 entry_font=None,
                 entry_background=None,
                 entry_foreground=None,
                 label_template=u"{nick}",
                 label_font=None,
                 logging_file=None,
                 tags=None):
        self.interior = Frame(master, class_="Chatbox")

        self._command = command

        self._is_empty = True

        self._maximum_lines = maximum_lines
        self._timestamp_template = timestamp_template

        self._command = command

        self._label_template = label_template

        self._logging_file = logging_file

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

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

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

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

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

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

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

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

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

        self._entry.focus()

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

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

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

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

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

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

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

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

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

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

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

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

        self.set_nick(my_nick)

    @property
    def topic(self):
        return

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

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

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

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

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

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

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

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

        self._write((content, tag))

    notification = notification_message

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

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

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

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

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

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

        self.user_message(self._my_nick, content)

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

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

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

        self._textarea.config(state=NORMAL)

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

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

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

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

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

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

        self._textarea.config(state=DISABLED)

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

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

        self.send(message)

        if self._command:
            self._command(message)

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

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

            self._entry_label["text"] = text
            self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry)
        else:
            self._entry_label.pack_forget()
class GeneratorDialog:
    # The UI to configure the settings by the user
    def __init__(self, root, ctrl):
        self.__root = root
        self.__ctrl = ctrl
        self.__pluginDir = os.path.dirname(
            os.path.abspath(inspect.stack()[0][1]))
        self.__ico = PhotoImage(file=self.__pluginDir +
                                '/pic/ScribusGenerator_logo.gif')
        root.tk.call('wm', 'iconphoto', root._w, '-default', self.__ico)

    def show(self):
        self.__root.title(CONST.APP_NAME)
        mainFrame = Frame(self.__root)

        top = mainFrame.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        mainFrame.rowconfigure(0, weight=1)
        mainFrame.columnconfigure(0, weight=1)
        mainFrame.grid(sticky='ew')

        # Three Sections: Input-Settings, Output-Settings and Buttons
        inputFrame = LabelFrame(mainFrame, text='Input Settings')
        inputFrame.columnconfigure(2, weight=1)
        inputFrame.grid(column=0, row=0, padx=5, pady=5, sticky='ew')
        outputFrame = LabelFrame(mainFrame, text='Output Settings')
        outputFrame.columnconfigure(2, weight=1)
        outputFrame.grid(column=0, row=1, padx=5, pady=5, sticky='ew')
        buttonFrame = Frame(mainFrame)
        buttonFrame.columnconfigure(3, weight=1)
        buttonFrame.grid(column=0, row=2, padx=5, pady=5, sticky='ew')

        # Input-Settings
        scribusSourceFileLabel = Label(inputFrame,
                                       text='Scribus File:',
                                       width=15,
                                       anchor='w')
        scribusSourceFileLabel.grid(column=0,
                                    row=0,
                                    padx=5,
                                    pady=5,
                                    sticky='w')
        scribusSourceFileEntry = Entry(
            inputFrame,
            textvariable=self.__ctrl.getScribusSourceFileEntryVariable())
        scribusSourceFileEntry.grid(column=1,
                                    columnspan=3,
                                    row=0,
                                    padx=5,
                                    pady=5,
                                    sticky='ew')
        scribusSourceFileButton = Button(
            inputFrame,
            text='⏏',
            command=self.__ctrl.scribusSourceFileEntryVariableHandler)
        scribusSourceFileButton.grid(column=4,
                                     row=0,
                                     padx=5,
                                     pady=5,
                                     sticky='e')
        scribusLoadSettingsButton = Button(
            inputFrame,
            text='↺',
            command=self.__ctrl.scribusLoadSettingsHandler)  # ⟲ ⟳ ↻ ↺ ⌂ ⌘ ⎗
        scribusLoadSettingsButton.grid(column=5,
                                       row=0,
                                       padx=5,
                                       pady=5,
                                       sticky='e')

        dataSourceFileLabel = Label(inputFrame,
                                    text='Data File:',
                                    width=15,
                                    anchor='w')
        dataSourceFileLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')
        dataSourceFileEntry = Entry(
            inputFrame,
            textvariable=self.__ctrl.getDataSourceFileEntryVariable())
        dataSourceFileEntry.grid(column=1,
                                 columnspan=4,
                                 row=1,
                                 padx=5,
                                 pady=5,
                                 sticky='ew')
        dataSourceFileButton = Button(
            inputFrame,
            text='⏏',
            command=self.__ctrl.dataSourceFileEntryVariableHandler)
        dataSourceFileButton.grid(column=5, row=1, padx=5, pady=5, sticky='e')

        dataSeparatorLabel = Label(inputFrame,
                                   text='Data Field Separator:',
                                   width=15,
                                   anchor='w')
        dataSeparatorLabel.grid(column=0, row=2, padx=5, pady=5, sticky='w')
        dataSeparatorEntry = Entry(
            inputFrame,
            width=3,
            textvariable=self.__ctrl.getDataSeparatorEntryVariable())
        dataSeparatorEntry.grid(column=1, row=2, padx=5, pady=5, sticky='w')

        fromLabel = Label(inputFrame,
                          text='(opt.) use partial data, only from:',
                          anchor='e')
        fromLabel.grid(column=2, row=2, padx=5, pady=5, sticky='e')
        fromEntry = Entry(inputFrame,
                          width=3,
                          textvariable=self.__ctrl.getFromVariable())
        fromEntry.grid(column=3, row=2, padx=5, pady=5, sticky='w')

        toLabel = Label(inputFrame, text='to:', width=3, anchor='e')
        toLabel.grid(column=4, row=2, padx=5, pady=5, sticky='e')
        toEntry = Entry(inputFrame,
                        width=3,
                        textvariable=self.__ctrl.getToVariable())
        toEntry.grid(column=5, row=2, padx=5, pady=5, sticky='w')

        # Output-Settings
        outputDirectoryLabel = Label(outputFrame,
                                     text='Output Directory:',
                                     width=15,
                                     anchor='w')
        outputDirectoryLabel.grid(column=0, row=0, padx=5, pady=5, sticky='w')
        outputDirectoryEntry = Entry(
            outputFrame,
            textvariable=self.__ctrl.getOutputDirectoryEntryVariable())
        outputDirectoryEntry.grid(column=1,
                                  columnspan=4,
                                  row=0,
                                  padx=5,
                                  pady=5,
                                  sticky='ew')
        outputDirectoryButton = Button(
            outputFrame,
            text='⏏',
            command=self.__ctrl.outputDirectoryEntryVariableHandler)
        outputDirectoryButton.grid(column=5, row=0, padx=5, pady=5, sticky='e')

        outputFileNameLabel = Label(outputFrame,
                                    text='Output File Name:',
                                    width=15,
                                    anchor='w')
        outputFileNameLabel.grid(column=0, row=1, padx=5, pady=5, sticky='w')
        outputFileNameEntry = Entry(
            outputFrame,
            textvariable=self.__ctrl.getOutputFileNameEntryVariable())
        outputFileNameEntry.grid(column=1,
                                 columnspan=3,
                                 row=1,
                                 padx=5,
                                 pady=5,
                                 sticky='ew')

        saveLabel = Label(outputFrame,
                          text='Save Settings:',
                          width=15,
                          anchor='w')
        saveLabel.grid(column=4, row=1, padx=5, pady=5, sticky='w')
        saveCheckbox = Checkbutton(
            outputFrame, variable=self.__ctrl.getSaveCheckboxVariable())
        saveCheckbox.grid(column=5, row=1, padx=5, pady=5, sticky='w')

        mergeOutputLabel = Label(outputFrame,
                                 text='Merge in Single File:',
                                 width=15,
                                 anchor='w')
        mergeOutputLabel.grid(column=0, row=2, padx=5, pady=5, sticky='w')
        mergeOutputCheckbox = Checkbutton(
            outputFrame, variable=self.__ctrl.getMergeOutputCheckboxVariable())
        mergeOutputCheckbox.grid(column=1, row=2, padx=5, pady=5, sticky='w')

        self.keepGeneratedScribusFilesLabel = Label(outputFrame,
                                                    text='Keep Scribus Files:',
                                                    width=15,
                                                    anchor='e')
        self.keepGeneratedScribusFilesLabel.grid(column=4,
                                                 row=2,
                                                 padx=5,
                                                 pady=5,
                                                 sticky='e')
        self.keepGeneratedScribusFilesCheckbox = Checkbutton(
            outputFrame,
            variable=self.__ctrl.getKeepGeneratedScribusFilesCheckboxVariable(
            ),
            anchor='w')
        self.keepGeneratedScribusFilesCheckbox.grid(column=5,
                                                    row=2,
                                                    padx=5,
                                                    pady=5,
                                                    sticky='w')

        outputFormatLabel = Label(outputFrame,
                                  text='Output Format:',
                                  anchor='e')
        outputFormatLabel.grid(column=2, row=2, padx=5, pady=5, sticky='e')
        outputFormatListBox = OptionMenu(
            outputFrame,
            self.__ctrl.getSelectedOutputFormat(),
            *self.__ctrl.getOutputFormatList(),
            command=lambda v=self.__ctrl.getSelectedOutputFormat(
            ): self.updateState(v))
        outputFormatListBox.grid(column=3, row=2, padx=5, pady=5, sticky='w')

        # Bottom Buttons
        generateButton = Button(buttonFrame,
                                text='✔\nGenerate',
                                width=10,
                                command=self.__ctrl.buttonOkHandler)
        generateButton.grid(column=0, row=0, padx=5, pady=5, sticky='w')
        cancelButton = Button(buttonFrame,
                              text='✘\nCancel',
                              width=10,
                              command=self.__ctrl.buttonCancelHandler)
        cancelButton.grid(column=1, row=0, padx=5, pady=5, sticky='e')
        helpButton = Button(buttonFrame,
                            text='❓\nHelp',
                            width=7,
                            command=self.__ctrl.helpButtonHandler)
        helpButton.grid(column=3, row=0, padx=5, pady=5, sticky='e')

        # general layout
        mainFrame.grid()
        self.__root.grid()

    def updateState(self, value):
        if (value == CONST.FORMAT_PDF):
            self.keepGeneratedScribusFilesLabel.configure(state=NORMAL)
            self.keepGeneratedScribusFilesCheckbox.configure(state=NORMAL)
        else:
            self.keepGeneratedScribusFilesLabel.configure(state=DISABLED)
            self.keepGeneratedScribusFilesCheckbox.configure(state=DISABLED)
Example #37
0
class MyQuestion(object):
    def __init__(self, parent, question_text, ans1_text, ans2_text, ans3_text,
                 ans4_text, exp1_text, exp2_text, exp3_text, exp4_text,
                 correct_ans):
        # assigning parameters to attributes
        self.parent = parent
        self.qtext = str(question_text)
        self.text1 = str(ans1_text)
        self.text2 = str(ans2_text)
        self.text3 = str(ans3_text)
        self.text4 = str(ans4_text)
        self.exp1 = str(exp1_text)
        self.exp2 = str(exp2_text)
        self.exp3 = str(exp3_text)
        self.exp4 = str(exp4_text)
        self.ans = int(correct_ans)

        # creating Tkinter variables
        self.ans_input = IntVar()
        self.is_correct = BooleanVar()
        self.efbg = StringVar()
        self.is_correct_text = StringVar()
        self.exp_text = StringVar()

        # developer mode
        if dev:
            self.ans_input.set(self.ans)

        # questionwide bgcolor, fgcolor
        self.bgcolor = GrayScale(80)
        self.fgcolor = GrayScale(20)

        # creating parent frame
        self.parent_frame()
        self.question_frame()

    def parent_frame(self):
        # creating parent frame
        self.pf = Frame(self.parent)
        self.pf.configure(bg=self.bgcolor)
        self.pf.place(relx=0, rely=0, relwidth=1, relheight=1)

    def question_frame(self):
        # creating question frame within parent frame
        self.qf = Frame(self.pf)
        self.qf.configure(bg=self.bgcolor)
        self.qf.place(relx=0, rely=0, relwidth=1, relheight=1)

        # creating objects within question frame
        self.title_label()
        self.radiobutton1()
        self.radiobutton2()
        self.radiobutton3()
        self.radiobutton4()
        self.check_ans_button()

    def explanation_frame(self):
        # creating explanation frame within parent frame
        self.ef = Frame(self.pf)
        self.ef.configure(bg=self.efbg.get())
        self.ef.place(relx=0, rely=0, relwidth=1, relheight=1)

        # creating objects within explanation frame
        self.is_correct_label()
        self.exp_label()
        self.next_ques_button()

        # creating display answer button if answer is wrong
        if not self.is_correct.get():
            self.disp_ans_button()

    def title_label(self):
        # creating title label for question frame
        self.tl = Label(self.qf)
        self.tl.configure(text=self.qtext)
        self.tl.configure(font=MyFonts['ExtraLarge'])
        self.tl.configure(bg=self.bgcolor, fg=self.fgcolor)
        self.tl.configure(relief=FLAT)
        self.tl.configure(padx=2, pady=2, anchor=N)
        self.tl.place(relx=0.05, rely=0.05, relwidth=0.90, relheight=0.10)

    def radiobutton1(self):
        # creating radiobuttion1 for question frame
        self.q1 = Radiobutton(self.qf)
        self.q1.configure(text='A. ' + self.text1)
        self.q1.configure(font=MyFonts['Large'])
        self.q1.configure(bg=self.bgcolor, activebackground=self.bgcolor)
        self.q1.configure(variable=self.ans_input, value=1)
        self.q1.place(relx=0.10, rely=0.20)

    def radiobutton2(self):
        # creating radiobutton2 for question frame
        self.q2 = Radiobutton(self.qf)
        self.q2.configure(text='B. ' + self.text2)
        self.q2.configure(font=MyFonts['Large'])
        self.q2.configure(bg=self.bgcolor, activebackground=self.bgcolor)
        self.q2.configure(variable=self.ans_input, value=2)
        self.q2.place(relx=0.10, rely=0.35)

    def radiobutton3(self):
        # creating radiobutton3 for question frame
        self.q3 = Radiobutton(self.qf)
        self.q3.configure(text='C. ' + self.text3)
        self.q3.configure(font=MyFonts['Large'])
        self.q3.configure(bg=self.bgcolor, activebackground=self.bgcolor)
        self.q3.configure(variable=self.ans_input, value=3)
        self.q3.place(relx=0.10, rely=0.50)

    def radiobutton4(self):
        # creating radiobutton4 for question frame
        self.q4 = Radiobutton(self.qf)
        self.q4.configure(text='D. ' + self.text4)
        self.q4.configure(font=MyFonts['Large'])
        self.q4.configure(bg=self.bgcolor, activebackground=self.bgcolor)
        self.q4.configure(variable=self.ans_input, value=4)
        self.q4.place(relx=0.10, rely=0.65)

    def check_ans_button(self):
        # creating check answer button for question frame
        self.cb = MyButton(self.qf, 'Check Answer', self.check_ans, 0.80, 0.85)

    def is_correct_label(self):
        # creating is_correct_label for explanation frame
        self.cl = Label(self.ef)
        self.cl.configure(text=self.is_correct_text.get())
        self.cl.configure(font=MyFonts['ExtraLargeBold'])
        self.cl.configure(bg=self.efbg.get(), fg=GrayScale(20))
        self.cl.configure(relief=FLAT)
        self.cl.configure(padx=2, pady=2, anchor=N)
        self.cl.place(relx=0.05, rely=0.05, relwidth=0.90, relheight=0.05)

    def exp_label(self):
        # creating exp_label for explanation frame
        self.el = Label(self.ef)
        self.el.configure(text=self.exp_text.get())
        self.el.configure(font=MyFonts['LargeBold'])
        self.el.configure(bg=self.efbg.get(), fg=GrayScale(20))
        self.el.configure(relief=FLAT)
        self.el.configure(padx=2, pady=2, anchor=N)
        self.el.place(relx=0.05, rely=0.10, relwidth=0.90, relheight=0.85)

    def next_ques_button(self):
        # creating next question button for explanation frame
        self.nq = MyButton(self.ef, 'Next Question', self.next_ques, 0.80,
                           0.85)

    def disp_ans_button(self):
        # creating display answer button for explanation frame
        self.da = MyButton(self.ef, 'Show Answer', self.disp_ans, 0.65, 0.85)

    def assign_all(self):
        # assigning correct answer text (ans_text) and explanation attributes (ans_exp)
        if self.ans == 1:
            self.ans_text = 'A. ' + self.text1
            self.ans_exp = self.exp1
        elif self.ans == 2:
            self.ans_text = 'B. ' + self.text2
            self.ans_exp = self.exp2
        elif self.ans == 3:
            self.ans_text = 'C. ' + self.text3
            self.ans_exp = self.exp3
        elif self.ans == 4:
            self.ans_text = 'D. ' + self.text4
            self.ans_exp = self.exp4
        else:
            self.ans_text = 'invalid correct_ans parameter'
            self.ans_exp = 'invalid correct_ans parameter'
            print 'invalid correct_ans parameter, please input between 1 and 4'

    def check_ans(self):
        # defining check answer function

        # is_correct (Boolean conditional)
        if self.ans_input.get() == self.ans:
            self.efbg.set(color_green)
            self.is_correct.set(True)
            self.is_correct_text.set('Correct Answer! :)')

        else:
            self.efbg.set(color_red)
            self.is_correct.set(False)
            self.is_correct_text.set('Wrong Answer :(')

            # only assign values for show answer if user answer is wrong
            self.assign_all()

        # appropriate response to selected answer
        if self.ans_input.get() == 1:
            self.exp_text.set(self.exp1)
            self.explanation_frame()
            self.qf.destroy()

        elif self.ans_input.get() == 2:
            self.exp_text.set(self.exp2)
            self.explanation_frame()
            self.qf.destroy()

        elif self.ans_input.get() == 3:
            self.exp_text.set(self.exp3)
            self.explanation_frame()
            self.qf.destroy()

        elif self.ans_input.get() == 4:
            self.exp_text.set(self.exp4)
            self.explanation_frame()
            self.qf.destroy()

        else:
            # no selected answer condition
            showerror('Error', 'Please select an answer to continue')

    def disp_ans(self):
        # defining display answer function
        tmp_str = self.ans_exp[0].lower() + self.ans_exp[1:]
        disp_ans_text = 'The correct answer is "' + str(
            self.ans_text) + '" because ' + str(tmp_str)
        showinfo('Correct Answer', disp_ans_text)

    def next_ques(self):
        # defininf next_question function
        self.pf.destroy()
        self.ef.destroy()
class Run(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initConfig()
        self.initUI()

    def initConfig(self):
        self.run = False
        self.patternText = np.array(["G", "X", "Y", "Z", "A", "B", "C"])
        self.lastText = np.array(
            ["0", "0.00", "0.00", "0.00", "0.00", "0.00", "0.00"])

        self.inputPos = np.array([0., 0., 300.])
        self.inputRot = np.array(
            [np.deg2rad(0.), np.deg2rad(0.),
             np.deg2rad(0.)])
        self.trajectory = np.array([[self.inputPos[0]], [self.inputPos[1]],
                                    [self.inputPos[2]]])
        self.lastPos = np.zeros(3)
        self.lastRot = np.zeros(3)
        self.machineOffset = np.array([0., 0., 800.])
        self.toolOffset = ([0, 0, 90])

        self.basePos = np.zeros((6, 3))
        self.platformPos = np.zeros((6, 3))
        self.prisma = np.zeros(3)
        self.prismaLength = np.zeros(6)
        self.dataPrismaLength = np.zeros((2, 6))
        self.travel = np.zeros(3)
        self.travelLength = 0
        self.travelVel = 0
        self.travelTime = 0
        self.timeSystem = 0

        self.rPlatform = 170.  # in mm
        self.rBase = 350.  # in mm

        self.minLength = 490.  # in mm
        self.maxLength = 740.  # in mm
        self.maxSpeed = 28.  # in mm/s

        self.thetaPlatform = np.array([
            np.deg2rad(45),
            np.deg2rad(75),
            np.deg2rad(165),
            np.deg2rad(-165),
            np.deg2rad(-75),
            np.deg2rad(-45)
        ])

        self.thetaBase = np.array([
            np.deg2rad(10),
            np.deg2rad(110),
            np.deg2rad(130),
            np.deg2rad(-130),
            np.deg2rad(-110),
            np.deg2rad(-10)
        ])

    def initUI(self):
        self.parent.title("5 AXIS STEWART CNC G-CODE READER")
        self.pack(fill=BOTH, expand=1)
        self.line = 1.0
        self.maxLine = 1.0
        self.lineNC = 1.0

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

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Open", command=self.onOpen)
        fileMenu.add_command(label="Clear", command=self.onClear)
        fileMenu.add_command(label="Save", command=self.onSave)
        fileMenu.add_command(label="Export", command=self.onExport)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)

        runMenu = Menu(menubar)
        runMenu.add_command(label="Initialize", command=self.onInit)
        runMenu.add_command(label="Run/Pause", command=self.onRun)
        runMenu.add_command(label="Stop", command=self.onStop)
        menubar.add_cascade(label="Run", menu=runMenu)

        self.execButton = Button(self, text="Execute", command=self.onExec)
        self.execButton.place(x=650, y=20)

        self.prevButton = Button(self, text="Prev", command=self.onPrev)
        self.prevButton.place(x=780, y=20)

        self.nextButton = Button(self, text="Next", command=self.onNext)
        self.nextButton.place(x=840, y=20)

        self.notif = "Application Started"

        self.lblGCode = Label(self, text="G-CODE")
        self.lblGCode.place(x=10, y=0)

        self.lblNC = Label(self, text="NC")
        self.lblNC.place(x=10, y=360)

        self.lblNotif = Label(self, text="Application Started")
        self.lblNotif.config(font=("Calibri", 20))
        self.lblNotif.place(x=1020, y=100)

        self.lblG = Label(self, text="G :")
        self.lblG.place(x=520, y=60)
        self.lblX = Label(self, text="X :")
        self.lblX.place(x=520, y=120)
        self.lblY = Label(self, text="Y :")
        self.lblY.place(x=520, y=150)
        self.lblZ = Label(self, text="Z :")
        self.lblZ.place(x=520, y=180)
        self.lblA = Label(self, text="A :")
        self.lblA.place(x=520, y=240)
        self.lblB = Label(self, text="B :")
        self.lblB.place(x=520, y=270)
        self.lblF = Label(
            self, text="F :                                       Time")
        self.lblF.place(x=520, y=330)

        self.lblL = Label(self, text="Link Length      -      Link Length/sec")
        self.lblL.place(x=680, y=80)
        self.lblL1 = Label(
            self,
            text=
            "1 :                         mm                                 mm/s"
        )
        self.lblL1.place(x=650, y=120)
        self.lblL2 = Label(
            self,
            text=
            "2 :                         mm                                 mm/s"
        )
        self.lblL2.place(x=650, y=150)
        self.lblL3 = Label(
            self,
            text=
            "3 :                         mm                                 mm/s"
        )
        self.lblL3.place(x=650, y=180)
        self.lblL4 = Label(
            self,
            text=
            "4 :                         mm                                 mm/s"
        )
        self.lblL4.place(x=650, y=210)
        self.lblL5 = Label(
            self,
            text=
            "5 :                         mm                                 mm/s"
        )
        self.lblL5.place(x=650, y=240)
        self.lblL6 = Label(
            self,
            text=
            "6 :                         mm                                 mm/s"
        )
        self.lblL6.place(x=650, y=270)

        self.txtGCode = Text(self, width=47, height=17)
        self.txtGCode.place(x=10, y=20)
        self.txtGCode.tag_configure('highlightline', background="#a9e9e9")
        self.txtGCode.config(font=("TkTextFont", 12))
        self._highlight_current_line()

        self.txtNC = Text(self, width=105, height=17)
        self.txtNC.place(x=10, y=380)
        self.txtNC.config(font=("TkTextFont", 10))

        self.txtG = Text(self, width=8, height=1)
        self.txtG.place(x=550, y=60)
        self.txtX = Text(self, width=8, height=1)
        self.txtX.place(x=550, y=120)
        self.txtY = Text(self, width=8, height=1)
        self.txtY.place(x=550, y=150)
        self.txtZ = Text(self, width=8, height=1)
        self.txtZ.place(x=550, y=180)
        self.txtA = Text(self, width=8, height=1)
        self.txtA.place(x=550, y=240)
        self.txtB = Text(self, width=8, height=1)
        self.txtB.place(x=550, y=270)
        self.txtF = Text(self, width=8, height=1)
        self.txtF.place(x=550, y=330)

        self.txtL1 = Text(self, width=10, height=1)
        self.txtL1.place(x=680, y=120)
        self.txtL2 = Text(self, width=10, height=1)
        self.txtL2.place(x=680, y=150)
        self.txtL3 = Text(self, width=10, height=1)
        self.txtL3.place(x=680, y=180)
        self.txtL4 = Text(self, width=10, height=1)
        self.txtL4.place(x=680, y=210)
        self.txtL5 = Text(self, width=10, height=1)
        self.txtL5.place(x=680, y=240)
        self.txtL6 = Text(self, width=10, height=1)
        self.txtL6.place(x=680, y=270)

        self.txtL1Dot = Text(self, width=10, height=1)
        self.txtL1Dot.place(x=840, y=120)
        self.txtL2Dot = Text(self, width=10, height=1)
        self.txtL2Dot.place(x=840, y=150)
        self.txtL3Dot = Text(self, width=10, height=1)
        self.txtL3Dot.place(x=840, y=180)
        self.txtL4Dot = Text(self, width=10, height=1)
        self.txtL4Dot.place(x=840, y=210)
        self.txtL5Dot = Text(self, width=10, height=1)
        self.txtL5Dot.place(x=840, y=240)
        self.txtL6Dot = Text(self, width=10, height=1)
        self.txtL6Dot.place(x=840, y=270)
        self.txtTime = Text(self, width=10, height=1)
        self.txtTime.place(x=760, y=330)

        self.f = Figure(figsize=(3.5, 3.5), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.f, self)
        self.canvas.draw()

        self.ax = Axes3D(self.f)
        self.ax.mouse_init()
        self.set_ax()

        self.canvas.get_tk_widget().place(x=890, y=320)

    def _highlight_current_line(self, interval=100):
        '''Updates the 'current line' highlighting every "interval" milliseconds'''
        self.txtGCode.tag_remove('highlightline', 1.0, "end")
        self.txtGCode.tag_add('highlightline', self.line,
                              str(int(self.line)) + '.end+1c')
        self.after(interval, self._highlight_current_line)

    def extractG(self):
        try:
            posG = self.txtGCode.search("G", self.line,
                                        str(int(self.line)) + '.end', 2)
            textG = self.txtGCode.get(posG + '+1c', posG + '+2c')
            self.txtG.insert(1.0, textG)
            self.lastText[0] = textG
        except:
            self.txtG.insert(1.0, self.lastText[0])
        return (self.txtG.get(1.0, 'end'))

    def extractX(self):
        try:
            posX = self.txtGCode.search("X", self.line,
                                        str(int(self.line)) + '.end', 6)
            textX = self.txtGCode.get(posX + '+1c', posX + '+6c')
            self.txtX.insert(1.0, textX)
            self.lastText[1] = textX
        except:
            self.txtX.insert(1.0, self.lastText[1])
        return (self.txtX.get(1.0, 'end'))

    def extractY(self):
        try:
            posY = self.txtGCode.search("Y", self.line,
                                        str(int(self.line)) + '.end', 6)
            textY = self.txtGCode.get(posY + '+1c', posY + '+6c')
            self.txtY.insert(1.0, textY)
            self.lastText[2] = textY
        except:
            self.txtY.insert(1.0, self.lastText[2])
        return (self.txtY.get(1.0, 'end'))

    def extractZ(self):
        try:
            posZ = self.txtGCode.search("Z", self.line,
                                        str(int(self.line)) + '.end', 6)
            textZ = self.txtGCode.get(posZ + '+1c', posZ + '+6c')
            self.txtZ.insert(1.0, textZ)
            self.lastText[3] = textZ
        except:
            self.txtZ.insert(1.0, self.lastText[3])
        return (self.txtZ.get(1.0, 'end'))

    def extractA(self):
        try:
            posA = self.txtGCode.search("A", self.line,
                                        str(int(self.line)) + '.end', 6)
            textA = self.txtGCode.get(posA + '+1c', posA + '+6c')
            self.txtA.insert(1.0, textA)
            self.lastText[4] = textA
        except:
            self.txtA.insert(1.0, self.lastText[4])
        return (self.txtA.get(1.0, 'end'))

    def extractB(self):
        try:
            posB = self.txtGCode.search("B", self.line,
                                        str(int(self.line)) + '.end', 6)
            textB = self.txtGCode.get(posB + '+1c', posB + '+6c')
            self.txtB.insert(1.0, textB)
            self.lastText[5] = textB
        except:
            self.txtB.insert(1.0, self.lastText[5])
        return (self.txtB.get(1.0, 'end'))

    def extractF(self):
        try:
            posF = self.txtGCode.search("F", self.line,
                                        str(int(self.line)) + '.end', 6)
            textF = self.txtGCode.get(posF + '+1c', posF + '+6c')
            self.txtF.insert(1.0, textF)
            self.lastText[6] = textF
        except:
            self.txtF.insert(1.0, self.lastText[6])
        return (self.txtF.get(1.0, 'end'))

    def draw(self):
        basePlate = np.array([
            np.append(self.basePos[:, 0], self.basePos[0, 0]),
            np.append(self.basePos[:, 1], self.basePos[0, 1]),
            np.append(self.basePos[:, 2], self.basePos[0, 2])
        ])
        platformPlate = np.array([
            np.append(self.platformPos[:, 0], self.platformPos[0, 0]),
            np.append(self.platformPos[:, 1], self.platformPos[0, 1]),
            np.append(self.platformPos[:, 2], self.platformPos[0, 2])
        ])

        self.ax.plot_trisurf(basePlate[0],
                             basePlate[1],
                             basePlate[2],
                             color='gray',
                             alpha=0.5)
        self.ax.plot_trisurf(platformPlate[0],
                             platformPlate[1],
                             platformPlate[2],
                             color='gray',
                             alpha=0.5)
        self.ax.plot_surface(basePlate[0],
                             basePlate[1],
                             np.array([basePlate[2], basePlate[2] - 50]),
                             color='gray')

        for i in range(6):
            self.ax.scatter(self.basePos[i, 0],
                            self.basePos[i, 1],
                            self.basePos[i, 2],
                            color="g",
                            s=25)
            self.ax.scatter(self.platformPos[i, 0],
                            self.platformPos[i, 1],
                            self.platformPos[i, 2],
                            color="g",
                            s=25)
            self.ax.plot3D([self.basePos[i, 0], self.platformPos[i, 0]],
                           [self.basePos[i, 1], self.platformPos[i, 1]],
                           [self.basePos[i, 2], self.platformPos[i, 2]])

        self.ax.plot3D([-400, 400], [0, 0], [0, 0], color="r")
        self.ax.plot3D([0, 0], [-400, 400], [0, 0], color="r")
        self.ax.plot3D([self.posMatrix[0], self.inputMatrix[0]],
                       [self.posMatrix[1], self.inputMatrix[1]],
                       [self.posMatrix[2], self.inputMatrix[2]])
        self.ax.scatter(self.posMatrix[0],
                        self.posMatrix[1],
                        self.posMatrix[2],
                        color="r",
                        s=10)
        self.ax.scatter(self.inputMatrix[0],
                        self.inputMatrix[1],
                        self.inputMatrix[2],
                        color="b",
                        s=10)

        self.ax.plot3D(self.trajectory[0, :],
                       self.trajectory[1, :],
                       self.trajectory[2, :],
                       color="g")
        #self.ax.plot3D(self.trajectoryG1[0,:], self.trajectoryG1[1,:], self.trajectoryG1[2,:], color="g")

    def writeNC(self):
        self.txtL1.insert(1.0, "{:.3f}".format(self.prismaLength[0]))
        self.txtL2.insert(1.0, "{:.3f}".format(self.prismaLength[1]))
        self.txtL3.insert(1.0, "{:.3f}".format(self.prismaLength[2]))
        self.txtL4.insert(1.0, "{:.3f}".format(self.prismaLength[3]))
        self.txtL5.insert(1.0, "{:.3f}".format(self.prismaLength[4]))
        self.txtL6.insert(1.0, "{:.3f}".format(self.prismaLength[5]))

        self.txtL1Dot.insert(1.0, "{:.3f}".format(self.dL[0]))
        self.txtL2Dot.insert(1.0, "{:.3f}".format(self.dL[1]))
        self.txtL3Dot.insert(1.0, "{:.3f}".format(self.dL[2]))
        self.txtL4Dot.insert(1.0, "{:.3f}".format(self.dL[3]))
        self.txtL5Dot.insert(1.0, "{:.3f}".format(self.dL[4]))
        self.txtL6Dot.insert(1.0, "{:.3f}".format(self.dL[5]))

        self.txtTime.insert(1.0, "{:.3f}".format(self.travelTime))

    def validator(self):
        if (self.shortPrismatic >= self.minLength) and (
                self.longPrismatic <= self.maxLength) and (
                    self.maxDL <= self.maxSpeed):  # check boundaries
            self.notif = "Executing Move Command"
            self.lblNotif.configure(text=self.notif, foreground="green")
            self.ax.cla()
            self.set_ax()
            self.draw()
            self.canvas.draw()


##            self.ij_prismaVel()
##            print(self.prismaVel)

        else:
            self.notif = "Move Command Couldn't Be Executed"
            self.lblNotif.configure(text=self.notif, foreground="red")
            self.onStop()

    def onExec(self):
        self.resetData()
        if int(self.extractG()) == 0:
            self.travelVel = 20.0
            self.txtF.insert(1.0, '20.0')
            self.inputPos = np.array([
                float(self.extractX()),
                float(self.extractY()),
                float(self.extractZ())
            ])
            self.inputRot = np.array([
                np.deg2rad(0.),
                np.deg2rad(float(self.extractB())),
                np.deg2rad(float(self.extractA()))
            ])

            self.trajectory = np.append(
                self.trajectory,
                [[self.inputPos[0]], [self.inputPos[1]], [self.inputPos[2]]],
                axis=1)
            self.ik_orientation()
            self.ik_position()

            self.dataPrismaLength[0, :] = self.ik_prismatic()

            if self.travelVel > 0:
                self.travelTime = self.travelLength / self.travelVel
                #print(self.travelTime)

            else:
                self.travelTime = 0.1

            if self.travelTime > 0:
                self.dL = (self.dataPrismaLength[0, :] -
                           self.dataPrismaLength[1, :]) / self.travelTime
            else:
                self.dL = np.zeros(6)

            self.timeSystem = self.timeSystem + self.travelTime
            self.travel = self.inputPos - self.lastPos
            self.travelLength = np.sqrt(np.dot(self.travel, self.travel.T))

            self.maxDL = np.max(np.abs(self.dL))

            self.writeNC()

            lbl = ["A", "B", "C", "D", "E", "F"]
            text1 = text2 = ""
            for i in range(0, 6):
                text1 += "L" + lbl[i] + "{:.2f} ".format(self.prismaLength[i])

            for i in range(0, 6):
                text2 += "dL" + lbl[i] + "{:.2f} ".format(self.dL[i])

            text = text1 + text2 + "T" + "{:.2f}".format(
                self.timeSystem) + "\n"

            self.txtNC.insert(self.lineNC, text)
            self.lineNC += 1

            self.lblNotif.update()
            self.lastPos = self.inputPos
            self.lastRot = self.inputRot
            self.dataPrismaLength[1, :] = self.dataPrismaLength[0, :]

            self.validator()

        else:
            self.travelVel = float(self.extractF())
            self.inputPos = np.array([
                float(self.extractX()),
                float(self.extractY()),
                float(self.extractZ())
            ])
            self.inputRot = np.array([
                np.deg2rad(0.),
                np.deg2rad(float(self.extractB())),
                np.deg2rad(float(self.extractA()))
            ])

            self.trajectory = np.append(
                self.trajectory,
                [[self.inputPos[0]], [self.inputPos[1]], [self.inputPos[2]]],
                axis=1)
            self.ik_orientation()
            self.ik_position()

            self.dataPrismaLength[0, :] = self.ik_prismatic()

            if self.travelVel > 0:
                self.travelTime = self.travelLength / self.travelVel

            else:
                self.travelTime = 0.1

            if self.travelTime > 0:
                self.dL = (self.dataPrismaLength[0, :] -
                           self.dataPrismaLength[1, :]) / self.travelTime
            else:
                self.dL = np.zeros(6)

            self.travel = self.inputPos - self.lastPos
            self.travelLength = np.sqrt(np.dot(self.travel, self.travel.T))

            self.maxDL = np.max(np.abs(self.dL))

            n = int(self.travelTime / 1.0)  #constant time for interpolation

            tempPosX = np.linspace(self.lastPos[0], self.inputPos[0], n)
            tempPosY = np.linspace(self.lastPos[1], self.inputPos[1], n)
            tempPosZ = np.linspace(self.lastPos[2], self.inputPos[2], n)
            tempRotA = np.linspace(self.lastRot[0], self.inputRot[0], n)
            tempRotB = np.linspace(self.lastRot[1], self.inputRot[1], n)
            tempTime = np.linspace(0, self.travelTime, n)

            for i in range(n):
                self.inputPos = np.array(
                    [tempPosX[i], tempPosY[i], tempPosZ[i]])
                self.inputRot = np.array(
                    [np.deg2rad(0.), tempRotB[i], tempRotA[i]])
                self.ik_orientation()
                self.ik_position()

                self.dataPrismaLength[0, :] = self.ik_prismatic()

                self.resetDataInterpolating()

                self.writeNC()

                lbl = ["A", "B", "C", "D", "E", "F"]
                text1 = text2 = ""
                for j in range(0, 6):
                    text1 += "L" + lbl[j] + "{:.2f} ".format(
                        self.prismaLength[j])

                for k in range(0, 6):
                    text2 += "dL" + lbl[k] + "{:.2f} ".format(self.dL[k])

                text = text1 + text2 + "T" + "{:.2f}".format(
                    self.timeSystem + tempTime[i]) + "\n"
                self.txtNC.insert(self.lineNC, text)
                self.lineNC += 1

            self.lblNotif.update()
            self.lastPos = self.inputPos
            self.lastRot = self.inputRot
            self.dataPrismaLength[1, :] = self.dataPrismaLength[0, :]

            self.timeSystem = self.timeSystem + self.travelTime
            self.validator()

    def onPrev(self):
        if self.line > 1.0:
            self.line -= 1.0
        else:
            self.line = 1.0

    def onNext(self):
        if self.line < self.maxLine:
            self.line += 1.0

    def onSave(self):
        name = tkFileDialog.asksaveasfile(mode='w', defaultextension=".gcode")
        text2save = str(self.txtGCode.get(0.0, END))
        name.write(text2save)
        name.close

    def onExport(self):
        name = tkFileDialog.asksaveasfile(mode='w', defaultextension=".spnc")
        text2save = str(self.txtNC.get(0.0, END))
        name.write(text2save)
        name.close

    def onClear(self):
        self.txtGCode.delete(1.0, 'end')
        self.txtNC.delete(1.0, 'end')
        self.trajectory = np.array([[self.inputPos[0]], [self.inputPos[1]],
                                    [self.inputPos[2]]])
        #self.trajectoryG0 = np.array([[self.inputPos[0]], [self.inputPos[1]], [self.inputPos[2]]])
        #self.trajectoryG1 = np.array([[self.inputPos[0]], [self.inputPos[1]], [self.inputPos[2]]])
        self.draw()
        self.canvas.draw()

    def onOpen(self):
        ftypes = [('G-code files', '*.gcode'), ('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        fl = dlg.show()

        if fl != '':
            text = self.readFile(fl)
            self.txtGCode.insert(1.0, text)
            self.maxLine = math.floor(float(self.txtGCode.index('end-1c')))

    def readFile(self, filename):
        f = open(filename, "r")
        text = f.read()
        return text

    def onInit(self):
        self.inputPos = np.array([0., 0., 300.])
        self.trajectory = np.array([[self.inputPos[0]], [self.inputPos[1]],
                                    [self.inputPos[2]]])
        #self.trajectoryG1 = np.array([[self.inputPos[0]], [self.inputPos[1]], [self.inputPos[2]]])
        self.line = 1.0
        self.timeSystem = 0
        self.onExec()

    def onRun(self):
        self.run = not self.run
        if self.run:
            print("Robot Started")
            self.notif = "Robot Started"
            self.lblNotif.configure(text=self.notif, foreground="blue")

            self.trajectory = np.delete(self.trajectory, 0, 1)
            #self.trajectoryG1 = np.delete(self.trajectoryG1, 0, 1)

            #time.sleep(5)
            while self.line <= self.maxLine:
                self.onExec()
                t = 0.
                while t < self.travelTime:
                    t += 0.1
                    #time.sleep(0.1)

                    # run control here

                if self.line == self.maxLine:
                    self.notif = "End of Process"
                    self.lblNotif.configure(text=self.notif, foreground="red")
                    self.onStop()

                if not self.run:
                    break

                self.notif = "Move Command Executed"
                self.lblNotif.configure(text=self.notif, foreground="blue")
                #time.sleep(5)

                self.onNext()

        else:
            print("Robot Paused")
            self.notif = "Robot Paused"
            self.lblNotif.configure(text=self.notif, foreground="red")

    def onStop(self):
        print("Robot Stopped")
        self.run = False

    def onExit(self):
        self.quit()
        self.destroy()

    def ik_prismatic(self):
        for i in range(6):
            self.basePos[i] = [
                self.rBase * np.cos(self.thetaBase[i]),
                self.rBase * np.sin(self.thetaBase[i]), 0
            ] + self.machineOffset
            self.platformPos[i] = [
                self.rPlatform * np.cos(self.thetaPlatform[i]),
                self.rPlatform * np.sin(self.thetaPlatform[i]), 0
            ]

        self.platformPos = np.dot(self.orientMatrix, self.platformPos.T)
        self.platformPos = self.posMatrix + self.platformPos.T
        self.prisma = self.platformPos - self.basePos

        for i in range(6):
            self.prismaLength[i] = np.sqrt(
                np.dot(self.prisma[i], self.prisma[i].T))

        self.shortPrismatic = np.min(self.prismaLength)
        self.longPrismatic = np.max(self.prismaLength)

        return self.prismaLength

    def ik_position(self):
        self.inputMatrix = np.array(
            [self.inputPos[0], self.inputPos[1], self.inputPos[2]])
        self.posMatrix = self.inputMatrix + np.dot(self.orientMatrix,
                                                   self.toolOffset)
        return self.posMatrix

    def ik_orientation(self):
        self.orientMatrix = np.array(
            [[
                np.cos(self.inputRot[0]) * np.cos(self.inputRot[1]),
                (np.cos(self.inputRot[0]) * np.sin(self.inputRot[1]) *
                 np.sin(self.inputRot[2])) -
                (np.sin(self.inputRot[0]) * np.cos(self.inputRot[2])),
                (np.cos(self.inputRot[0]) * np.sin(self.inputRot[1]) *
                 np.cos(self.inputRot[2])) +
                (np.sin(self.inputRot[0]) * np.sin(self.inputRot[2]))
            ],
             [
                 np.sin(self.inputRot[0]) * np.cos(self.inputRot[1]),
                 (np.sin(self.inputRot[0]) * np.sin(self.inputRot[1]) *
                  np.sin(self.inputRot[2])) +
                 (np.cos(self.inputRot[0]) * np.cos(self.inputRot[2])),
                 (np.sin(self.inputRot[0]) * np.sin(self.inputRot[1]) *
                  np.cos(self.inputRot[2])) -
                 (np.cos(self.inputRot[0]) * np.sin(self.inputRot[2]))
             ],
             [
                 -np.sin(self.inputRot[1]),
                 np.cos(self.inputRot[1]) * np.sin(self.inputRot[2]),
                 np.cos(self.inputRot[1]) * np.cos(self.inputRot[2])
             ]])
        return self.orientMatrix

    def ij_constant(self):
        for i in range(6):
            self.basePos[i] = [
                self.rBase * np.cos(self.thetaBase[i]),
                self.rBase * np.sin(self.thetaBase[i]), 0
            ] + self.machineOffset
            self.platformPos[i] = [
                self.rPlatform * np.cos(self.thetaPlatform[i]),
                self.rPlatform * np.sin(self.thetaPlatform[i]), 0
            ]

        c1 = np.dot(self.orientMatrix, self.platformPos.T)
        c1T = np.transpose(c1)
        c2 = np.cross(c1, self.prisma)
        c2T = np.transpose(c2)
        c3 = np.dot(c1T, c2T)
        return c3

    def ij_variable(self):
        dLinear = self.inputPos - self.lastPos
        dAngular = self.inputRot - self.lastRot
        self.velocity = np.array([self.dLinear, self.dAngular])
        return self.velocity

    def ij_invDiagLength(self):
        diag = np.diag(self.prismaLength)
        invDiag = np.linalg.inv(diag)
        return invDiag

    def ij_prismaVel(self):
        temp = np.dot(self.ij_constant(), self.ij_variable())
        prismaVel = np.dot(self.ij_invDiagLength(), temp)
        return prismaVel

    def set_ax(self):  #ax panel set up
        self.ax.set_aspect("equal")
        self.ax.set_xlim3d(-400, 400)
        self.ax.set_ylim3d(-400, 400)
        self.ax.set_zlim3d(0, 800)
        self.ax.set_xlabel('X axis')
        self.ax.set_ylabel('Y axis')
        self.ax.set_zlabel('Z axis')
        self.ax.set_axisbelow(True)  #send grid lines to the background

    def resetData(self):
        self.txtG.delete(1.0, 'end')
        self.txtA.delete(1.0, 'end')
        self.txtB.delete(1.0, 'end')
        self.txtX.delete(1.0, 'end')
        self.txtY.delete(1.0, 'end')
        self.txtZ.delete(1.0, 'end')
        self.txtF.delete(1.0, 'end')
        self.txtL1.delete(1.0, 'end')
        self.txtL2.delete(1.0, 'end')
        self.txtL3.delete(1.0, 'end')
        self.txtL4.delete(1.0, 'end')
        self.txtL5.delete(1.0, 'end')
        self.txtL6.delete(1.0, 'end')
        self.txtL1Dot.delete(1.0, 'end')
        self.txtL2Dot.delete(1.0, 'end')
        self.txtL3Dot.delete(1.0, 'end')
        self.txtL4Dot.delete(1.0, 'end')
        self.txtL5Dot.delete(1.0, 'end')
        self.txtL6Dot.delete(1.0, 'end')
        self.txtTime.delete(1.0, 'end')

    def resetDataInterpolating(self):
        self.txtL1.delete(1.0, 'end')
        self.txtL2.delete(1.0, 'end')
        self.txtL3.delete(1.0, 'end')
        self.txtL4.delete(1.0, 'end')
        self.txtL5.delete(1.0, 'end')
        self.txtL6.delete(1.0, 'end')
        self.txtL1Dot.delete(1.0, 'end')
        self.txtL2Dot.delete(1.0, 'end')
        self.txtL3Dot.delete(1.0, 'end')
        self.txtL4Dot.delete(1.0, 'end')
        self.txtL5Dot.delete(1.0, 'end')
        self.txtL6Dot.delete(1.0, 'end')
        self.txtTime.delete(1.0, 'end')
Example #39
0
top_frame.pack(fill=X)
lbl_help = Label(top_frame, bg="#222", fg="#EEE", pady=10,
                 text="Por favor selecione a imagem que deseja converter."
                      "\n\nIMPORTANTE:"
                      "\n -> Os arquivos devem ser em formato bmp, jpg ou png"
                      "\n -> As imagens devem ser simples e com poucos detalhes"
                      "\n -> Os arquivos devem ser menores que 6kB",
                 justify=LEFT)
lbl_help.pack(fill=X)
# Top Frame End
# Middle frame start
middle_frame = Frame(master_frame)
middle_frame.pack(fill=BOTH, expand=True)
tk_image = ImageTk.PhotoImage(Image.open(c_path+'bitmap.gif'))
img_label = Label(middle_frame, bg="#999", bd=15, padx=20, pady=20, relief=FLAT)
img_label.configure(image=tk_image)
img_label.place(relx=0.5, rely=0.5, anchor=CENTER)
# Middle Frame end

# Frame2 Begin
bottom_frame = Frame(master_frame)
bottom_frame.pack(fill=X)
file_entry = Label(bottom_frame, bg="#222", fg="#EEE", justify=LEFT, relief=SUNKEN)
s_btn = Button(bottom_frame, activebackground="#111", bg="#222", fg="#EEE",
               text="Enviar para impressora", justify=CENTER, command=send_file)  # , state=DISABLED)

sel_btn = Button(bottom_frame, activebackground="#111", bg="#222", fg="#EEE",
                 text="Selecione o Arquivo", justify=CENTER, command=select_file)
file_entry.pack(fill=BOTH, pady=5, padx=5, expand=True)
s_btn.pack(side=RIGHT, anchor=N, padx=5, pady=5)
sel_btn.pack(side=RIGHT, anchor=N, padx=5, pady=5)
Example #40
0
class CollapsibleFrame(Frame):
    def __init__(self,
                 master,
                 text=None,
                 borderwidth=2,
                 width=0,
                 height=16,
                 interior_padx=0,
                 interior_pady=8,
                 background=None,
                 caption_separation=4,
                 caption_font=None,
                 caption_builder=None,
                 icon_x=5):
        Frame.__init__(self, master)
        if background is None:
            background = self.cget("background")

        self.configure(background=background)

        self._is_opened = False

        self._interior_padx = interior_padx
        self._interior_pady = interior_pady

        self._iconOpen = PhotoImage(
            data=
            "R0lGODlhEAAQAKIAAP///9TQyICAgEBAQAAAAAAAAAAAAAAAACwAAAAAEAAQAAADNhi63BMgyinFAy0HC3Xj2EJoIEOM32WeaSeeqFK+say+2azUi+5ttx/QJeQIjshkcsBsOp/MBAA7"
        )
        self._iconClose = PhotoImage(
            data=
            "R0lGODlhEAAQAKIAAP///9TQyICAgEBAQAAAAAAAAAAAAAAAACwAAAAAEAAQAAADMxi63BMgyinFAy0HC3XjmLeA4ngpRKoSZoeuDLmo38mwtVvKu93rIo5gSCwWB8ikcolMAAA7"
        )

        height_of_icon = max(self._iconOpen.height(), self._iconClose.height())
        width_of_icon = max(self._iconOpen.width(), self._iconClose.width())

        containerFrame_pady = (height_of_icon // 2) + 1

        self._height = height
        self._width = width

        self._containerFrame = Frame(self,
                                     borderwidth=borderwidth,
                                     width=width,
                                     height=height,
                                     relief=RIDGE,
                                     background=background)
        self._containerFrame.pack(expand=True,
                                  fill=X,
                                  pady=(containerFrame_pady, 0))

        self.interior = Frame(self._containerFrame, background=background)

        self._collapseButton = Label(self,
                                     borderwidth=0,
                                     image=self._iconOpen,
                                     relief=RAISED)
        self._collapseButton.place(in_=self._containerFrame,
                                   x=icon_x,
                                   y=-(height_of_icon // 2),
                                   anchor=N + W,
                                   bordermode="ignore")
        self._collapseButton.bind("<Button-1>", lambda event: self.toggle())

        if caption_builder is None:
            self._captionLabel = Label(self,
                                       anchor=W,
                                       borderwidth=1,
                                       text=text)
            if caption_font is not None:
                self._captionLabel.configure(font=caption_font)
        else:
            self._captionLabel = caption_builder(self)

            if not isinstance(self._captionLabel, Widget):
                raise Exception(
                    "'caption_builder' doesn't return a tkinter widget")

        self.after(
            0, lambda: self._place_caption(caption_separation, icon_x,
                                           width_of_icon))

    def update_width(self, width=None):
        # Update could be devil
        # http://wiki.tcl.tk/1255
        self.after(0, lambda width=width: self._update_width(width))

    def _place_caption(self, caption_separation, icon_x, width_of_icon):
        self.update()
        x = caption_separation + icon_x + width_of_icon
        y = -(self._captionLabel.winfo_reqheight() // 2)

        self._captionLabel.place(in_=self._containerFrame,
                                 x=x,
                                 y=y,
                                 anchor=N + W,
                                 bordermode="ignore")

    def _update_width(self, width):
        self.update()
        if width is None:
            width = self.interior.winfo_reqwidth()

        if isinstance(self._interior_pady, (list, tuple)):
            width += self._interior_pady[0] + self._interior_pady[1]
        else:
            width += 2 * self._interior_pady

        width = max(self._width, width)

        self._containerFrame.configure(width=width)

    def open(self):
        self._collapseButton.configure(image=self._iconClose)

        self._containerFrame.configure(height=self.interior.winfo_reqheight())
        self.interior.pack(expand=True,
                           fill=X,
                           padx=self._interior_padx,
                           pady=self._interior_pady)

        self._is_opened = True

    def close(self):
        self.interior.pack_forget()
        self._containerFrame.configure(height=self._height)
        self._collapseButton.configure(image=self._iconOpen)

        self._is_opened = False

    def toggle(self):
        if self._is_opened:
            self.close()
        else:
            self.open()
Example #41
0
class MainWindow(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.wm_title("FRCA QBase Reader - Exam Mode")
        w, h = self.winfo_screenwidth(), self.winfo_screenheight()
        self.geometry("%dx%d+0+0" % (w, h))
        self.bind("<Down>", self.OnSmaller)
        self.bind("<Up>", self.OnBigger)
        self.bind("<Right>", self.nextQuestion)
        self.logic = Logic()
        self.widgetwraplist = []
        self.text = self.logic.prepareQuestion()
        self.font = tkFont.Font(size=24)
        self.stmtvar = StringVar()
        self.stmtvar.set(self.text['question'][0])
        self.statement = Label(self, textvariable=self.stmtvar, font=self.font)
        self.statement.pack(anchor = W)
        self.widgetwraplist.append(self.statement)
        self.checkbuttons = {}
        self.checkbtntext = {}
        self.checkbuttonvar = {}        
        for i in range(1, 6):
            self.checkbuttonvar[str(i)] = BooleanVar()
            self.checkbtntext[str(i)] = StringVar()
            self.checkbtntext[str(i)].set(self.text['question'][i])
            self.checkbuttons['question '+str(i)] = InvokableCheckbutton(self,
                              textvariable = self.checkbtntext[str(i)],
                              variable = self.checkbuttonvar[str(i)],
                              font=self.font)
            self.checkbuttons['question '+str(i)].pack(anchor = W)
            self.widgetwraplist.append(self.checkbuttons['question '+str(i)])         
            self.bind("<Key-"+str(i)+">", self.checkbuttons['question '+str(i)].customInvoke)
        self.explvar = StringVar()
        self.explvar.set(' '.join(self.text['question'][6:]))
        self.explanation = Label(self, textvariable=self.explvar,
                                 font=self.font, justify=LEFT)
        self.widgetwraplist.append(self.explanation)
        self.buttonNext = Button(self, text = 'Next question',
                                 command = lambda: self.nextQuestion(1),
                                 font=self.font)
        self.buttonNext.pack(anchor = S)

    def nextQuestion(self, event):
        given_answers = []
        self.logic.questioncount += 1
        for i in range(1, 6):
            given_answers.append(self.logic.str2bool(self.checkbuttonvar[str(i)].get()))
        self.logic.questiondict[self.logic.questionpath]['given answers'] = given_answers
        if (self.logic.questiondict[self.logic.questionpath]['correct answers'] == 
            self.logic.questiondict[self.logic.questionpath]['given answers']):
                self.logic.questiondict[self.logic.questionpath]['is correct'] = True
        else:
            self.logic.questiondict[self.logic.questionpath]['is correct'] = False
        if self.logic.questioncount < self.logic.EXAM_END:
            if self.logic.questioncount == self.logic.EXAM_END-1:
                self.buttonNext.configure(text='Finish exam')
            self.text = self.logic.prepareQuestion()
            self.stmtvar.set(self.text['question'][0])
            self.explvar.set(' '.join(self.text['question'][6:]))
            self.explanation.pack_forget()
            for i in range(1, 6):
                self.checkbuttons['question '+str(i)].configure(fg='black')
                self.checkbuttonvar[str(i)].set(False)
                self.checkbtntext[str(i)].set(self.text['question'][i])
        else:
            self.stmtvar.set('You scored {}%'.format(str(self.logic.calculateScore())))
            if self.logic.calculateScore() >= 80:
                self.statement.configure(foreground='#009E18')
            else:
                self.statement.configure(foreground='red')
            for i in range(1, 6):
                self.checkbuttons['question '+str(i)].pack_forget()
            if self.logic.calculateScore() == 100:
                self.buttonNext.configure(text='Start a new exam')
                self.buttonNext.configure(command=lambda: self.startNewExam(1))
                self.bind("<Right>", self.startNewExam)
            else:
                self.bind("<Right>", self.reviewWindow)
                self.buttonNext.configure(text='Review wrong answers')
                self.buttonNext.configure(command= lambda: self.reviewWindow(1))

    def reviewWindow(self, event):
        self.reviewed = 0
        self.buttonNext.configure(text='Next')
        self.buttonNext.pack_forget()
        for i in range(1, 6):
            self.checkbuttons['question '+str(i)].pack(anchor = W)
        self.explanation.pack(anchor = W)
        self.buttonNext.pack(anchor = S)
        self.showAnswer(1)

    def showAnswer(self, event):
        if self.reviewed == 0:
            self.bind("<Right>", self.showAnswer)
            self.buttonNext.configure(command= lambda: self.showAnswer(1))
        for q in self.logic.questiondict:
            if self.logic.questiondict[q]['is correct'] == False:
                f = open(q, 'r')
                lines = self.logic.parseQuestion(f)
                self.stmtvar.set(lines['question'][0])
                self.statement.configure(foreground='black')
                self.explvar.set(' '.join(lines['question'][6:]))
                for i in range(1, 6):
                    self.checkbtntext[str(i)].set(lines['question'][i])
                    self.checkbuttonvar[str(i)].set(self.logic.questiondict[q]['given answers'][i-1])
                    if (self.logic.questiondict[q]['correct answers'][i-1] == 
                        self.logic.questiondict[q]['given answers'][i-1]):
                        self.checkbuttons['question '+str(i)].configure(fg='#009E18')
                    else:
                        self.checkbuttons['question '+str(i)].configure(fg='red')
                del self.logic.questiondict[q]
                self.reviewed += 1
                break
        if self.reviewed == self.logic.EXAM_END:
            self.buttonNext.configure(text='Start a new exam')
            self.buttonNext.configure(command=lambda: self.startNewExam(1))
            self.bind("<Right>", self.startNewExam)
            
    def startNewExam(self, event):
        self.logic.questioncount = 0
        self.questiondict = {}
        self.text = self.logic.prepareQuestion()
        self.stmtvar.set(self.text['question'][0])
        for i in range(1, 6):
                self.checkbuttons['question '+str(i)].configure(fg='black')
                self.checkbuttonvar[str(i)].set(False)
                self.checkbtntext[str(i)].set(self.text['question'][i])
        self.explanation.pack_forget()
        self.buttonNext.configure(text='next')
        self.buttonNext.configure(command=lambda: self.nextQuestion(1))
        self.bind("<Right>", self.nextQuestion)            

    def OnBigger(self, event):
        '''Make the font 2 points bigger'''
        size = self.font['size']
        self.font.configure(size=size+2)

    def OnSmaller(self, event):
        '''Make the font 2 points smaller'''
        size = self.font['size']
        self.font.configure(size=size-2)

    def wrapWidgets(self):
        self.update()
        for widget in self.widgetwraplist:
            widget.configure(wraplength=self.winfo_width())
Example #42
0
    def init_UI(self):

        self.parent.title('Liquid Thermal Shock Tester v0.2')
        self.pack(fill=BOTH, expand=True)
        options_frame = Frame(self, background='gray', pady=5, padx=5)
        options_frame.pack(side=LEFT, fill=BOTH, expand=True)

        options_label = Label(options_frame,
                              text='Test Setup',
                              background='gray',
                              font=('Courier', 22, 'bold'),
                              justify=LEFT)
        ul_bold_font = Font(options_label, options_label.cget('font'))
        ul_bold_font.configure(underline=True)
        options_label.configure(font=ul_bold_font)
        options_label.pack(anchor=CENTER, side=TOP, padx=5, pady=5)

        cycles_frame = Frame(options_frame, background='gray', pady=5)
        cycles_frame.pack(side=TOP, fill=BOTH, expand=True)

        cycles_label = Label(cycles_frame,
                             text='# of cycles',
                             background='gray',
                             font=('Courier', 12),
                             justify=CENTER)
        cycles_label.grid(row=0,
                          column=0,
                          rowspan=1,
                          columnspan=2,
                          sticky='news')
        ul_plain_font = Font(cycles_label, cycles_label.cget('font'))
        ul_plain_font.configure(underline=True)
        cycles_label.configure(font=ul_plain_font)

        self.cycles_select_disp = Label(cycles_frame,
                                        text='5',
                                        background='white',
                                        font=('Courier', 32))
        self.cycles_select_disp.grid(row=1,
                                     column=0,
                                     rowspan=2,
                                     columnspan=1,
                                     sticky='wens',
                                     padx=5,
                                     pady=5)

        self.cycles_increase_button = Button(cycles_frame,
                                             text=u'\u25b2',
                                             font=('Courier', 18, 'bold'),
                                             command=self.cycles_increment)
        self.cycles_increase_button.grid(row=1,
                                         column=1,
                                         rowspan=1,
                                         columnspan=1,
                                         sticky='wens',
                                         padx=5,
                                         pady=5)

        self.cycles_decrease_button = Button(cycles_frame,
                                             text=u'\u25BC',
                                             font=('Courier', 18, 'bold'),
                                             command=self.cycles_decrement)
        self.cycles_decrease_button.grid(row=2,
                                         column=1,
                                         rowspan=1,
                                         columnspan=1,
                                         sticky='wens',
                                         padx=5,
                                         pady=5)

        self.fix_grid(cycles_frame)

        soak_time_frame = Frame(options_frame, background='gray', pady=5)
        soak_time_frame.pack(side=TOP, fill=BOTH, expand=True)

        soak_time_label = Label(soak_time_frame,
                                text='Minutes per Soak',
                                background='gray',
                                font=('Courier', 12),
                                justify=CENTER)
        soak_time_label.grid(row=0,
                             column=0,
                             rowspan=1,
                             columnspan=2,
                             sticky='news')
        soak_time_label.configure(font=ul_plain_font)

        self.soak_time_disp = Label(soak_time_frame,
                                    text='5',
                                    background='white',
                                    font=('Courier', 32))
        self.soak_time_disp.grid(row=1,
                                 column=0,
                                 rowspan=2,
                                 columnspan=1,
                                 sticky='wens',
                                 padx=5,
                                 pady=5)

        self.soak_time_increment_button = Button(
            soak_time_frame,
            text=u'\u25b2',
            font=('Courier', 18, 'bold'),
            command=self.soak_time_increment)
        self.soak_time_increment_button.grid(row=1,
                                             column=1,
                                             rowspan=1,
                                             columnspan=1,
                                             sticky='wens',
                                             padx=5,
                                             pady=5)

        self.soak_time_decrement_button = Button(
            soak_time_frame,
            text=u'\u25BC',
            font=('Courier', 18, 'bold'),
            command=self.soak_time_decrement)
        self.soak_time_decrement_button.grid(row=2,
                                             column=1,
                                             rowspan=1,
                                             columnspan=1,
                                             sticky='wens',
                                             padx=5,
                                             pady=5)

        self.fix_grid(soak_time_frame)

        controls_frame = Frame(self, background='gray')
        controls_frame.pack(side=LEFT, fill=BOTH, expand=True)

        run_pause_frame = Frame(controls_frame, background='gray')
        run_pause_frame.pack(side=TOP, fill=BOTH, expand=True, pady=5)

        self.run_button = Button(run_pause_frame,
                                 text='RUN',
                                 background='green',
                                 activebackground='green',
                                 font=('Courier', 30, 'bold'),
                                 width=5,
                                 command=self.run_init)
        self.run_button.grid(row=0, column=0, sticky='wens', padx=5, pady=5)

        self.pause_button = Button(run_pause_frame,
                                   text='PAUSE',
                                   background='orange',
                                   activebackground='orange',
                                   font=('Courier', 30, 'bold'),
                                   width=5,
                                   command=self.pause_button_pressed)
        self.pause_button.grid(row=0, column=1, sticky='wens', padx=5, pady=5)

        self.fix_grid(run_pause_frame)

        stop_button = Button(controls_frame,
                             text='STOP',
                             background='red',
                             activebackground='red',
                             font=('Courier', 36, 'bold'),
                             command=self.stop_test)
        stop_button.pack(side=TOP, fill=BOTH, expand=True, padx=5)

        jog_frame = Frame(controls_frame, background='gray')
        jog_frame.pack(side=TOP, fill=BOTH, expand=True, pady=5)

        jog_label = Label(jog_frame,
                          text='Motor\rjog',
                          font=('Courier', 12, 'bold'),
                          background='gray')
        jog_label.grid(row=1, column=1)

        self.jog_up_button = Button(jog_frame,
                                    text=u'\u25b2',
                                    font=('Courier', 18, 'bold'))
        self.jog_up_button.grid(row=0,
                                column=1,
                                rowspan=1,
                                columnspan=1,
                                sticky='wens',
                                padx=5,
                                pady=5)
        self.jog_up_button.bind("<Button-1>", self.jog_up_on)
        self.jog_up_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_left_button = Button(jog_frame,
                                      text=u'\u25C4',
                                      font=('Courier', 18, 'bold'))
        self.jog_left_button.grid(row=1,
                                  column=0,
                                  rowspan=1,
                                  columnspan=1,
                                  sticky='wens',
                                  padx=5,
                                  pady=5)
        self.jog_left_button.bind("<Button-1>", self.jog_left_on)
        self.jog_left_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_right_button = Button(jog_frame,
                                       text=u'\u25BA',
                                       font=('Courier', 18, 'bold'))
        self.jog_right_button.grid(row=1,
                                   column=2,
                                   rowspan=1,
                                   columnspan=1,
                                   sticky='wens',
                                   padx=5,
                                   pady=5)
        self.jog_right_button.bind("<Button-1>", self.jog_right_on)
        self.jog_right_button.bind("<ButtonRelease-1>", self.jog_off)

        self.jog_down_button = Button(jog_frame,
                                      text=u'\u25BC',
                                      font=('Courier', 18, 'bold'))
        self.jog_down_button.grid(row=2,
                                  column=1,
                                  rowspan=1,
                                  columnspan=1,
                                  sticky='wens',
                                  padx=5,
                                  pady=5)
        self.jog_down_button.bind("<Button-1>", self.jog_down_on)
        self.jog_down_button.bind("<ButtonRelease-1>", self.jog_off)

        self.fix_grid(jog_frame)

        status_frame = Frame(self, background='gray')
        status_frame.pack(side=LEFT, fill=BOTH, expand=True, padx=5, pady=5)

        status_label = Label(status_frame,
                             text='Tester Status',
                             background='gray',
                             font=('Courier', 22, 'bold'),
                             justify=LEFT)
        status_label.configure(font=ul_bold_font)
        status_label.pack(anchor=CENTER, side=TOP, padx=5, pady=5)

        self.status_disp = Text(status_frame)
        self.status_disp.pack(side=TOP, fill=BOTH, padx=5, pady=5)
        self.status_disp.configure(state='disabled')

        self.power_button = Button(status_frame,
                                   text='POWER OFF',
                                   font=('Courier', 24, 'bold'),
                                   background="red",
                                   activebackground="red",
                                   command=self.shutdown,
                                   height=2)
        self.power_button.pack(side=TOP, fill=BOTH, padx=5, pady=5)
Example #43
0
class Viewer():
    def __init__(self, image):
        self.original = image
        self.image = image.copy()
        self.window = Tk()

        self.genViews()
        self.currentView = StringVar(self.window)
        self.currentView.set('Original')
        options = self.filters.keys()
        options.sort()
        self.views = OptionMenu(self.window,
                                self.currentView,
                                *options,
                                command=self.applyFilter)
        self.views.pack()

        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage = Label(image=self.tkImage)
        self.lblImage.bind('<Button-1>', self.displayInfos)
        self.lblImage.bind('<Button-3>', self.save)
        self.lblImage.image = self.tkImage
        self.lblImage.pack()

        self.status = StringVar()
        self.lblStatus = Label(textvariable=self.status, justify='right')
        self.lblStatus.pack()

        self.window.mainloop()

    def displayInfos(self, event):
        """
        Displays the coordinates in the status bar
        """
        x = int((event.x - 0.1) / args.scalefactor)
        y = int((event.y - 0.1) / args.scalefactor)
        pixel = orig.getpixel((x, y))
        self.setStatus("Coordinates : (%s:%s) - Pixel value : %s" %
                       (x, y, str(pixel)))

    def setStatus(self, text):
        """
        Changes the text in the status bar
        """
        self.status.set(text)

    def save(self, event):
        """
        Saves the filtered image to a file
        """
        options = {'filetypes': [('PNG', '.png'), ('GIF', '.gif')]}
        outfile = tkFileDialog.asksaveasfilename(**options)
        if outfile == '':
            return
        else:
            self.image.save(outfile)
            return

    def genViews(self):
        """
        Generates filters based on the source image
        """
        self.filters = {}
        for plug in viewPlugins:
            self.filters.update({plug.name: viewPlugins.index(plug)})

    def applyFilter(self, view):
        """
        Applies a filter to the image
        """
        view = self.filters[self.currentView.get()]
        plugin = viewPlugins[view]
        if plugin.parameters:
            for param in plugin.parameters.keys():
                a = tkSimpleDialog.askinteger('Question',
                                              plugin.parameters[param])
                if a is not None:
                    setattr(viewPlugins[view], param, a)
        self.image = viewPlugins[view].process(self.original)

        self.showImage(self.currentView.get(), self.image)
        self.setStatus("")
        return

    def showImage(self, title, image):
        """
        Updates the image in the window
        """
        self.tkImage = ImageTk.PhotoImage(image)
        self.lblImage.configure(image=self.tkImage)
        self.lblImage.image = self.tkImage
class VideoSelectionScreen(GuiBaseFrame):
    def __init__(self, parent, controller, **kw):
        GuiBaseFrame.__init__(self, parent, controller, **kw)

    def init_widgets(self):
        self.content_wrapper = Frame(self)

        self.init_video_info()

        self.screen_title_label = Header1Label(self.content_wrapper,
                                               text="Video Selection")
        self.instruction_label = PLabel(
            self.content_wrapper,
            text="Please choose your left and right video files. "
            "Press Next when finished.\n"
            "(Files must be in MKV format).")
        self.left_video_filename_preview_label = PLabel(
            self.content_wrapper, text="No Video Selected")
        self.left_video_button = Button(
            self.content_wrapper,
            text="Choose Left Video",
            command=lambda: self.select_video_through_button_press(LEFT))
        self.right_video_filename_preview_label = PLabel(
            self.content_wrapper, text="No Video Selected")
        self.right_video_button = Button(
            self.content_wrapper,
            text="Choose Right Video",
            command=lambda: self.select_video_through_button_press(RIGHT))
        self.next_button = Button(self.content_wrapper,
                                  text="Next",
                                  state=DISABLED,
                                  command=lambda: self.next_screen())

        self.add_img_previews()

    def add_widgets_to_frame(self):
        self.content_wrapper.grid_columnconfigure(0, weight=1)
        self.content_wrapper.grid_columnconfigure(1, weight=1)

        self.screen_title_label.grid(row=SCREEN_TITLE_ROW,
                                     column=0,
                                     columnspan=CENTER_SCREEN_COLSPAN)
        self.instruction_label.grid(row=INSTRUCTION_ROW,
                                    column=LEFT_VIDEO_THUMBNAIL_COL,
                                    columnspan=CENTER_SCREEN_COLSPAN)

        self.left_video_thumbnail.grid(row=THUMBNAIL_ROW,
                                       column=LEFT_VIDEO_THUMBNAIL_COL)
        self.left_video_filename_preview_label.grid(
            row=FILENAME_PREVIEW_ROW, column=LEFT_VIDEO_THUMBNAIL_COL)
        self.left_video_button.grid(row=CHOOSE_VIDEO_BUTTON_ROW,
                                    column=LEFT_VIDEO_THUMBNAIL_COL)

        self.right_video_thumbnail.grid(row=THUMBNAIL_ROW,
                                        column=RIGHT_VIDEO_THUMBNAIL_COL)
        self.right_video_filename_preview_label.grid(
            row=FILENAME_PREVIEW_ROW, column=RIGHT_VIDEO_THUMBNAIL_COL)
        self.right_video_button.grid(row=CHOOSE_VIDEO_BUTTON_ROW,
                                     column=RIGHT_VIDEO_THUMBNAIL_COL)

        self.next_button.grid(row=NEXT_BUTTON_ROW,
                              column=0,
                              columnspan=CENTER_SCREEN_COLSPAN)
        self.content_wrapper.place(relx=SCREENS_REL_X,
                                   rely=SCREEN_REL_Y_47,
                                   anchor=CENTER)

    def init_video_info(self):
        self.left_video_selected = False
        self.right_video_selected = False
        self.left_video_filename = None
        self.right_video_filename = None

    def next_screen(self):
        self.controller.set_video_filenames(self.left_video_filename,
                                            self.right_video_filename)
        self.controller.show_next_frame()

    def add_img_previews(self):
        img_not_available = cv2.imread(
            get_asset_filename(IMG_NOT_AVAILABLE_FILENAME))
        img_not_available = cv2_bgr_image_to_tkinter_with_resize(
            img_not_available, VIDEO_PREVIEW_WIDTH, VIDEO_PREVIEW_HEIGHT)

        self.left_video_thumbnail = Label(self.content_wrapper,
                                          image=img_not_available)
        self.left_video_thumbnail.image = img_not_available
        self.right_video_thumbnail = Label(self.content_wrapper,
                                           image=img_not_available)
        self.right_video_thumbnail.image = img_not_available

    def select_video_through_button_press(self, video_side=LEFT):
        selected_video_filename = select_video_filename()
        self.set_video_thumbnail_based_on_filename(selected_video_filename,
                                                   video_side)

    def set_next_button_state(self):
        if self.left_video_selected and self.right_video_selected:
            self.next_button.configure(state=NORMAL)

    def on_show_frame(self):
        if does_tmp_file_exist_basename(VIDEOS_SELECTED_TMP_FILENAME):
            video_filenames = read_tmp_file(VIDEOS_SELECTED_TMP_FILENAME)
            video_filenames = ast.literal_eval(video_filenames)
            self.set_video_thumbnail_based_on_filename(video_filenames[LEFT],
                                                       LEFT)
            self.set_video_thumbnail_based_on_filename(video_filenames[RIGHT],
                                                       RIGHT)

    def on_hide_frame(self):
        video_filenames_used = {
            LEFT: self.left_video_filename,
            RIGHT: self.right_video_filename
        }
        write_to_tmp_file(VIDEOS_SELECTED_TMP_FILENAME,
                          str(video_filenames_used))

    def set_video_thumbnail_based_on_filename(self,
                                              video_filename,
                                              video_side=LEFT):
        if os.path.isfile(
                os.path.join(os.path.dirname(video_filename),
                             os.path.basename(video_filename))):
            vc_object = cv2.VideoCapture(video_filename)
            _, img = vc_object.read()
            vc_object.release()

            img = cv2_bgr_image_to_tkinter_with_resize(img,
                                                       VIDEO_PREVIEW_WIDTH,
                                                       VIDEO_PREVIEW_HEIGHT)
            self.update_ui(video_filename, img, True, video_side)

    def update_ui(self, filename, img, video_selected, video_side=LEFT):
        if video_selected and video_side == LEFT:
            self.left_video_selected = True
            self.left_video_filename = filename
            self.left_video_filename_preview_label.config(
                text=os.path.basename(os.path.normpath(filename)))
            self.set_next_button_state()

            self.left_video_thumbnail.configure(image=img)
            self.left_video_thumbnail.image = img
        elif video_selected and video_side == RIGHT:
            self.right_video_selected = True
            self.right_video_filename = filename
            self.right_video_filename_preview_label.config(
                text=os.path.basename(os.path.normpath(filename)))
            self.set_next_button_state()

            self.right_video_thumbnail.configure(image=img)
            self.right_video_thumbnail.image = img
Example #45
0
class KeyboardEntry:
    """Mixin class that can be used to add the ability to type values for
widget.  When the cursor enters the widget the focus is set to the widget
and the widget that had the focus previousy is saved in .lastFocus.
When the cursor leaves the widget focus is restored to self.lastFocus.

key_cb(event) is called upon KeyRelease events. If this is the first keytroke
an undecorated window is created next to the cursor and handleKeyStroke(event)
is called.  This method should be subclassed to modify the way the string is
typed in (see thumbwheel.py for an example of handling numbers only).
When the Return key is pressed, the entry window is destroyed and if the
typed striong is not empty self.callSet(self.typedValue) is called.

If the cursor moves out of the widget before Rrturn is pressed the value
in the entry window is discarded and the entry window is destroyed.
"""
    def __init__(self, widgets, callSet):
        # callSet is a function taking one argument (string) which will be
        # when the Returnm key is hit (if the typed string is not empty)
        # widgets is a list of Tkinter wigets for which <Enter>, <Leave>
        # <Return> and <KeyRelease> are handled. These widgets has to exist
        # before thsi constructor can be called
        assert callable(callSet)
        self.callSet = callSet
        for w in widgets:
            w.bind("<Enter>", self.enter_cb)
            w.bind("<Leave>", self.leave_cb)
            w.bind("<Return>", self.return_cb)
            w.bind("<KeyRelease>", self.key_cb)

        self.typedValue = ''  # string accumulating valuescharacters typed
        self.lastFocus = None  # widget to which the focus will be restored
        # when the mouse leaves the widget
        self.topEntry = None  # top level for typing values
        self.typedValueTK = None  #Tk label used as entry for value

    def key_cb(self, event=None):
        # call back function for keyboard events (except for Return)
        # handle numbers to set value
        key = event.keysym
        if key == 'Return': return

        #print 'Key:', key
        if len(self.typedValue) == 0 and self.topEntry is None:
            # create Tk label showing typed value
            x = event.x
            y = event.y

            #print 'create entry'
            self.topEntry = Toplevel()
            self.topEntry.overrideredirect(1)
            w = event.widget
            if event.x >= 0:
                self.topEntry.geometry('+%d+%d' %
                                       (w.winfo_rootx() + event.x + 10,
                                        w.winfo_rooty() + event.y))
            else:
                self.topEntry.geometry('+%d+%d' %
                                       (w.winfo_rootx() + 10, w.winfo_rooty()))
            self.typedValueTK = Label(master=self.topEntry,
                                      text='',
                                      relief='sunken',
                                      bg='yellow')
            self.typedValueTK.pack()

        self.handleKeyStroke(event)

    def leave_cb(self, event=None):
        # make sure widget gets keyboard events
        # print 'leave', event.widget

        if self.topEntry:
            self.typedValueTK.destroy()
            self.topEntry.destroy()
            self.topEntry = None
        self.typedValue = ''
        if self.lastFocus:
            #print 'restoring focus'
            if widgetsOnBackWindowsCanGrabFocus is False:
                lActiveWindow = self.lastFocus.focus_get()
                if    lActiveWindow is not None \
                  and ( lActiveWindow.winfo_toplevel() != self.lastFocus.winfo_toplevel() ):
                    return

            self.lastFocus.focus_set()
            self.lastFocus = None
            event.widget.config(cursor='')

    def enter_cb(self, event=None):
        # make sure widget gets keyboard events
        #print 'enter', event.widget

        if widgetsOnBackWindowsCanGrabFocus is False:
            lActiveWindow = event.widget.focus_get()
            if    lActiveWindow is not None \
              and ( lActiveWindow.winfo_toplevel() != event.widget.winfo_toplevel() ):
                return

        if self.lastFocus is None:
            #print 'setting focus'
            self.lastFocus = self.focus_lastfor()
        event.widget.focus_set()
        event.widget.config(cursor='xterm')

    def return_cb(self, event):
        # return should destroy the topEntry
        #print "return_cb"
        if self.typedValueTK is not None:
            self.typedValueTK.destroy()
        if self.topEntry is not None:
            self.topEntry.destroy()
        self.topEntry = None
        if len(self.typedValue):
            #print 'setting to', self.type(self.typedValue)
            self.callSet(self.typedValue)
        self.typedValue = ''

    ## TO BE SUBCLASSED

    def handleKeyStroke(self, event):
        # by default we handle delete character keys
        key = event.keysym
        if key == 'BackSpace' or key == 'Delete':
            self.typedValue = self.typedValue[:-1]
            self.typedValueTK.configure(text=self.typedValue)
Example #46
0
File: ui_heap.py Project: an-o/Sub
class UIHeap(object):
    """
       Interface object for a heap 

    """

    def __init__(self, frame, position, h_center, v_center):
        self._h_center = h_center
        self._v_center = v_center
        # Memorise the frame
        self.frame = frame

        self.position = position

        # Memorise the card in the heap
        self._heap = None
        # The image itself 
        self._heap_image = None 
        # The label index
        self._label_index = None
        self._init_label()


    def label_column(self):
        """ 
            Define the position for the heap

        """
        if self.position == 0 or self.position == 2:
            # Base
            column = self._h_center 
        elif self.position == 1 or self.position == 3:
            # Base 
            column = self._h_center
            # Small shifting 
            h_shift = 60 
            if self.position == 1:
                # Shift it to the right 
                column += h_shift
            elif self.position == 3:
                # Shift it to the left
                column -= h_shift
            # Don't forget to center it
        column -= ImageLoader.CARD_WIDTH / 2.0
        return column 


    def label_row(self):
        """
            Return the row (pixel) of the heap according to its player position

        """
        row = UIPositioning.first_card_row[self.position] 
        vert_shift = 15 
        if self.position == 0:
            # Shift it down
            row += 1.5*ImageLoader.CARD_HEIGHT
            # A little higher
            row -= vert_shift
        elif self.position == 2:
            # Shift it up
            row -= 1.5 * ImageLoader.CARD_HEIGHT
            # Down down down
            row += vert_shift

        return row 
        

    def _place_label(self):
        """
            Place the label to its position

        """
        # Need to destroy it to place it on top of others cards
        self._label.destroy()
        self._init_label()
        self._set_image()
        self._label.place(x = self.label_column(), y = self.label_row())


    def _init_label(self):
        """
            Init the label 

        """
        self._label = Label(self.frame)


    def _set_image(self):
        """
            Set the image using the current image 

        """
        self._label.configure(image = self._heap_image)
        


    def _update_heap_image(self):
        """
            Update the card image 
        """
        # Remove or update the image ?
        if self.heap is None:
            # Remove the image
            self._label.place_forget()
            self._heap_image = None
        else:
            # Get a new card
            new_card = UICard.get_card_image(self.heap)
            # Save it
            self._heap_image = new_card
            # Replace it
            self._place_label()


    @property
    def heap(self):
        return self._heap


    @heap.setter
    def heap(self, value):
        self._heap = value
        self._update_heap_image()
Example #47
0
class EMNN():
    def __init__(self, conn):
        conn.gui = True
        queue = self.queue = Queue.Queue()
        conn.queue = queue
        self.conn = conn

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.scrollbar = Scrollbar(self.root)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        elif option == "Options":

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

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

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

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

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

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

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

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

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

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

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

            self.aucstate()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    vstack = vsource = vlocals = vglobals = None

    def __init__(self, pyshell, idb=None):
        if idb is None:
            idb = Idb(self)
        self.pyshell = pyshell
        self.idb = idb
        self.frame = None
        self.make_gui()
        self.interacting = 0
        self.nesting_level = 0

    def run(self, *args):
        # Deal with the scenario where we've already got a program running
        # in the debugger and we want to start another. If that is the case,
        # our second 'run' was invoked from an event dispatched not from
        # the main event loop, but from the nested event loop in 'interaction'
        # below. So our stack looks something like this:
        #       outer main event loop
        #         run()
        #           <running program with traces>
        #             callback to debugger's interaction()
        #               nested event loop
        #                 run() for second command
        #
        # This kind of nesting of event loops causes all kinds of problems
        # (see e.g. issue #24455) especially when dealing with running as a
        # subprocess, where there's all kinds of extra stuff happening in
        # there - insert a traceback.print_stack() to check it out.
        #
        # By this point, we've already called restart_subprocess() in
        # ScriptBinding. However, we also need to unwind the stack back to
        # that outer event loop.  To accomplish this, we:
        #   - return immediately from the nested run()
        #   - abort_loop ensures the nested event loop will terminate
        #   - the debugger's interaction routine completes normally
        #   - the restart_subprocess() will have taken care of stopping
        #     the running program, which will also let the outer run complete
        #
        # That leaves us back at the outer main event loop, at which point our
        # after event can fire, and we'll come back to this routine with a
        # clean stack.
        if self.nesting_level > 0:
            self.abort_loop()
            self.root.after(100, lambda: self.run(*args))
            return
        try:
            self.interacting = 1
            return self.idb.run(*args)
        finally:
            self.interacting = 0

    def close(self, event=None):
        try:
            self.quit()
        except Exception:
            pass
        if self.interacting:
            self.top.bell()
            return
        if self.stackviewer:
            self.stackviewer.close()
            self.stackviewer = None
        # Clean up pyshell if user clicked debugger control close widget.
        # (Causes a harmless extra cycle through close_debugger() if user
        # toggled debugger from pyshell Debug menu)
        self.pyshell.close_debugger()
        # Now close the debugger control window....
        self.top.destroy()

    def make_gui(self):
        pyshell = self.pyshell
        self.flist = pyshell.flist
        self.root = root = pyshell.root
        self.top = top = ListedToplevel(root)
        self.top.wm_title("Debug Control")
        self.top.wm_iconname("Debug")
        top.wm_protocol("WM_DELETE_WINDOW", self.close)
        self.top.bind("<Escape>", self.close)
        #
        self.bframe = bframe = Frame(top)
        self.bframe.pack(anchor="w")
        self.buttons = bl = []
        #
        self.bcont = b = Button(bframe, text="Go", command=self.cont)
        bl.append(b)
        self.bstep = b = Button(bframe, text="Step", command=self.step)
        bl.append(b)
        self.bnext = b = Button(bframe, text="Over", command=self.next)
        bl.append(b)
        self.bret = b = Button(bframe, text="Out", command=self.ret)
        bl.append(b)
        self.bret = b = Button(bframe, text="Quit", command=self.quit)
        bl.append(b)
        #
        for b in bl:
            b.configure(state="disabled")
            b.pack(side="left")
        #
        self.cframe = cframe = Frame(bframe)
        self.cframe.pack(side="left")
        #
        if not self.vstack:
            self.__class__.vstack = BooleanVar(top)
            self.vstack.set(1)
        self.bstack = Checkbutton(cframe,
                                  text="Stack",
                                  command=self.show_stack,
                                  variable=self.vstack)
        self.bstack.grid(row=0, column=0)
        if not self.vsource:
            self.__class__.vsource = BooleanVar(top)
        self.bsource = Checkbutton(cframe,
                                   text="Source",
                                   command=self.show_source,
                                   variable=self.vsource)
        self.bsource.grid(row=0, column=1)
        if not self.vlocals:
            self.__class__.vlocals = BooleanVar(top)
            self.vlocals.set(1)
        self.blocals = Checkbutton(cframe,
                                   text="Locals",
                                   command=self.show_locals,
                                   variable=self.vlocals)
        self.blocals.grid(row=1, column=0)
        if not self.vglobals:
            self.__class__.vglobals = BooleanVar(top)
        self.bglobals = Checkbutton(cframe,
                                    text="Globals",
                                    command=self.show_globals,
                                    variable=self.vglobals)
        self.bglobals.grid(row=1, column=1)
        #
        self.status = Label(top, anchor="w")
        self.status.pack(anchor="w")
        self.error = Label(top, anchor="w")
        self.error.pack(anchor="w", fill="x")
        self.errorbg = self.error.cget("background")
        #
        self.fstack = Frame(top, height=1)
        self.fstack.pack(expand=1, fill="both")
        self.flocals = Frame(top)
        self.flocals.pack(expand=1, fill="both")
        self.fglobals = Frame(top, height=1)
        self.fglobals.pack(expand=1, fill="both")
        #
        if self.vstack.get():
            self.show_stack()
        if self.vlocals.get():
            self.show_locals()
        if self.vglobals.get():
            self.show_globals()

    def interaction(self, message, frame, info=None):
        self.frame = frame
        self.status.configure(text=message)
        #
        if info:
            type, value, tb = info
            try:
                m1 = type.__name__
            except AttributeError:
                m1 = "%s" % str(type)
            if value is not None:
                try:
                    m1 = "%s: %s" % (m1, str(value))
                except:
                    pass
            bg = "yellow"
        else:
            m1 = ""
            tb = None
            bg = self.errorbg
        self.error.configure(text=m1, background=bg)
        #
        sv = self.stackviewer
        if sv:
            stack, i = self.idb.get_stack(self.frame, tb)
            sv.load_stack(stack, i)
        #
        self.show_variables(1)
        #
        if self.vsource.get():
            self.sync_source_line()
        #
        for b in self.buttons:
            b.configure(state="normal")
        #
        self.top.wakeup()
        # Nested main loop: Tkinter's main loop is not reentrant, so use
        # Tcl's vwait facility, which reenters the event loop until an
        # event handler sets the variable we're waiting on
        self.nesting_level += 1
        self.root.tk.call('vwait', '::idledebugwait')
        self.nesting_level -= 1
        #
        for b in self.buttons:
            b.configure(state="disabled")
        self.status.configure(text="")
        self.error.configure(text="", background=self.errorbg)
        self.frame = None

    def sync_source_line(self):
        frame = self.frame
        if not frame:
            return
        filename, lineno = self.__frame2fileline(frame)
        if filename[:1] + filename[-1:] != "<>" and os.path.exists(filename):
            self.flist.gotofileline(filename, lineno)

    def __frame2fileline(self, frame):
        code = frame.f_code
        filename = code.co_filename
        lineno = frame.f_lineno
        return filename, lineno

    def cont(self):
        self.idb.set_continue()
        self.abort_loop()

    def step(self):
        self.idb.set_step()
        self.abort_loop()

    def next(self):
        self.idb.set_next(self.frame)
        self.abort_loop()

    def ret(self):
        self.idb.set_return(self.frame)
        self.abort_loop()

    def quit(self):
        self.idb.set_quit()
        self.abort_loop()

    def abort_loop(self):
        self.root.tk.call('set', '::idledebugwait', '1')

    stackviewer = None

    def show_stack(self):
        if not self.stackviewer and self.vstack.get():
            self.stackviewer = sv = StackViewer(self.fstack, self.flist, self)
            if self.frame:
                stack, i = self.idb.get_stack(self.frame, None)
                sv.load_stack(stack, i)
        else:
            sv = self.stackviewer
            if sv and not self.vstack.get():
                self.stackviewer = None
                sv.close()
            self.fstack['height'] = 1

    def show_source(self):
        if self.vsource.get():
            self.sync_source_line()

    def show_frame(self, stackitem):
        self.frame = stackitem[0]  # lineno is stackitem[1]
        self.show_variables()

    localsviewer = None
    globalsviewer = None

    def show_locals(self):
        lv = self.localsviewer
        if self.vlocals.get():
            if not lv:
                self.localsviewer = NamespaceViewer(self.flocals, "Locals")
        else:
            if lv:
                self.localsviewer = None
                lv.close()
                self.flocals['height'] = 1
        self.show_variables()

    def show_globals(self):
        gv = self.globalsviewer
        if self.vglobals.get():
            if not gv:
                self.globalsviewer = NamespaceViewer(self.fglobals, "Globals")
        else:
            if gv:
                self.globalsviewer = None
                gv.close()
                self.fglobals['height'] = 1
        self.show_variables()

    def show_variables(self, force=0):
        lv = self.localsviewer
        gv = self.globalsviewer
        frame = self.frame
        if not frame:
            ldict = gdict = None
        else:
            ldict = frame.f_locals
            gdict = frame.f_globals
            if lv and gv and ldict is gdict:
                ldict = None
        if lv:
            lv.load_dict(ldict, force, self.pyshell.interp.rpcclt)
        if gv:
            gv.load_dict(gdict, force, self.pyshell.interp.rpcclt)

    def set_breakpoint_here(self, filename, lineno):
        self.idb.set_break(filename, lineno)

    def clear_breakpoint_here(self, filename, lineno):
        self.idb.clear_break(filename, lineno)

    def clear_file_breaks(self, filename):
        self.idb.clear_all_file_breaks(filename)

    def load_breakpoints(self):
        "Load PyShellEditorWindow breakpoints into subprocess debugger"
        pyshell_edit_windows = self.pyshell.flist.inversedict.keys()
        for editwin in pyshell_edit_windows:
            filename = editwin.io.filename
            try:
                for lineno in editwin.breakpoints:
                    self.set_breakpoint_here(filename, lineno)
            except AttributeError:
                continue
class GetCfgSectionNameDialog(Toplevel):
    def __init__(self, parent, title, message, usedNames):
        """
        message - string, informational message to display
        usedNames - list, list of names already in use for validity check
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        self.resizable(height=False, width=False)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self.Cancel)
        self.parent = parent
        self.message = message
        self.usedNames = usedNames
        self.result = ''
        self.CreateWidgets()
        self.withdraw() #hide while setting geometry
        self.update_idletasks()
        self.geometry("+%d+%d" %
            ((parent.winfo_rootx() + ((parent.winfo_width() / 2)
                - (self.winfo_reqwidth() / 2)),
              parent.winfo_rooty() + ((parent.winfo_height() / 2)
                - (self.winfo_reqheight() / 2)) )) ) #centre dialog over parent
        self.deiconify() #geometry set, unhide
        self.wait_window()

    def CreateWidgets(self):
        self.name = StringVar(self)
        self.fontSize = StringVar(self)
        self.frameMain = Frame(self, borderwidth=2, relief=SUNKEN)
        self.messageInfo = Label(self.frameMain, text=self.message)
        entryName = Entry(self.frameMain, textvariable=self.name, width=30)
        frameButtons = Frame(self)
        self.buttonOk = Button(frameButtons, text='Ok', command=self.Ok)
        self.buttonCancel = Button(frameButtons, text='Cancel',
                command=self.Cancel)

        entryName.focus_set()

        self.frameMain.pack(side=TOP, expand=True, fill=BOTH)
        self.messageInfo.pack(padx=5, pady=5)
        entryName.pack(padx=5, pady=5)
        frameButtons.pack(side=BOTTOM, fill=X)
        self.buttonOk.pack(padx=1, pady=5, side=RIGHT)
        self.buttonCancel.pack(pady=5, padx=5, side=RIGHT)

        if TTK:
            self.messageInfo['padding'] = 5
            frameButtons['style'] = 'RootColor.TFrame'
        else:
            self.messageInfo.configure(padx=5, pady=5)

    def NameOk(self):
        #simple validity check for a sensible
        #ConfigParser file section name
        nameOk = 1
        name = self.name.get()
        name.strip()

        if not name: #no name specified
            tkMessageBox.showerror(title='Name Error',
                message='No name specified.', parent=self)
            nameOk = 0
        elif len(name) > 30: #name too long
            tkMessageBox.showerror(title='Name Error',
                message=('Name too long. It should be no more than '
                         '30 characters.'), parent=self)
            nameOk=0
        elif name in self.usedNames:
            tkMessageBox.showerror(title='Name Error',
                    message='This name is already in use.', parent=self)
            nameOk=0

        return nameOk

    def Ok(self, event=None):
        if self.NameOk():
            self.result = self.name.get().strip()
            self.destroy()

    def Cancel(self, event=None):
        self.result = ''
        self.destroy()
Example #50
0
class Sleepy(Frame):
    clock = None
    calendar = None
    weather = None
    temperature = None

    def __init__(self, parent):
        Frame.__init__(self, parent, background=Palette.background)
        self.parent = parent
        self.pack(fill=TkC.BOTH, expand=1)

        # init the clock
        clock_font = tkFont.Font(family='Droid Sans', size=52, weight='bold')
        self.clock = Label(self, text="??:??", fg=Palette.primary, bg=Palette.background, font=clock_font)
        self.clock.place(x=0, y=0)

        # init the calendar
        calendar_font = tkFont.Font(family='Droid Sans', size=12)
        self.calendar = Label(self, text="?? ?????, ???", fg=Palette.secondary, bg=Palette.background, font=calendar_font)
        self.calendar.place(x=4, y=70)

        # init the weather
        self.weather = Weather(self, 320, 82)
        self.weather.place(x=0, y=(240 - 82))

        # init the temperature
        temperature_font = tkFont.Font(family='Droid Sans', size=12)
        self.temperature = Label(self, text="?? °C", fg=Palette.secondary, bg=Palette.background, font=temperature_font)
        self.temperature.place(x=240, y=50)

        # print tkFont.families()
        # ('Century Schoolbook L', 'Droid Sans Mono', 'Droid Sans Ethiopic', 'Droid Sans Thai', 'DejaVu Sans Mono', 'URW Palladio L', 'Droid Arabic Naskh', 'URW Gothic L', 'Dingbats', 'URW Chancery L', 'FreeSerif', 'DejaVu Sans', 'Droid Sans Japanese', 'Droid Sans Georgian', 'Nimbus Sans L', 'Droid Serif', 'Droid Sans Hebrew', 'Droid Sans Fallback', 'Standard Symbols L', 'Nimbus Mono L', 'Nimbus Roman No9 L', 'FreeSans', 'DejaVu Serif', 'Droid Sans Armenian', 'FreeMono', 'URW Bookman L', 'Droid Sans')

        # start working
        self.update_clock()
        self.update_temperature()
        self.fetch_weather_thread()

    def update_clock(self):
        """
        Updates the clock every ten seconds (less precision = less stuff to do)
        """
        now = time.strftime("%H:%M")
        self.clock.configure(text=now)
        cal = time.strftime("%A, %B %d")
        self.calendar.configure(text=cal)

        self.parent.after(10000, self.update_clock)

    def update_temperature(self):
        """
        Update the temperature every minute
        """
        t = sensor.DS18B20(simulate=True) #FIXME should be set from CLI parameter
        temp = "%0.2f °C" % (t.read_temp())
        self.temperature.configure(text=temp)
        self.parent.after(60*1000, self.update_temperature)

    def fetch_weather_thread(self):
        """
        start a thread to fetch new weather data
        """
        thread.start_new_thread(self.fetch_weather, ())

    def fetch_weather(self):
        """
        fetch new weather data
        """
        apikey = "f4b0ead5b6a13da37d586a327730ae0b"  # FIXME move to config
        location = "Berlin,de"

        values = {
            'q': location,
            'APPID': apikey,
            'mode': json
        }

        try:
            response = urllib2.urlopen('http://api.openweathermap.org/data/2.5/forecast?' + urllib.urlencode(values))
            data = response.read()
            weather_data = json.loads(data)
            self.weather.update_data(weather_data)

            # call again in 1 hour
            self.parent.after(1000 * 60 * 60, self.fetch_weather_thread)
        except urllib2.URLError as e:
            print e.reason
            # call again in 1 minute
            self.parent.after(1000 * 60 * 1, self.fetch_weather_thread)
Example #51
0
class GUIRunner(Toplevel):

    #===========================================================================
    # fields to set in the GUI
    #===========================================================================

    info_text = None
    paddingArgs = {'padx':3, 'pady':3}

    def __init__(self, parent):
        '''
        Constructor.
        '''
        Toplevel.__init__(self, parent)
        self.wm_withdraw()
        self.resizable(height = FALSE, width = FALSE)
        #self.wm_deiconify()

        self.url = StringVar()
        self.login = IntVar()
        self.user = StringVar()
        self.password = StringVar()

        self.master = parent
        self.configure(borderwidth = 5)
        self.init_gui()

    def init_gui(self):
        '''
        Initialize a simple gui.
        '''
        top = Frame(self.master)
        top.grid(**self.paddingArgs)

        frame = Frame(top)
        frame.grid(column = 0, row = 0, columnspan = 2)

        text = Label(frame, text = 'OCCI service URL:')
        text.grid(column = 0, row = 0, **self.paddingArgs)

        self.url.set('http://localhost:8888')
        entry = Entry(frame, width = 25, textvariable = self.url)
        entry.grid(column = 1, row = 0, **self.paddingArgs)

        go = Button(frame, text = 'Go', command = self.run_tests)
        go.grid(column = 2, row = 0, **self.paddingArgs)

        reset = Button(frame, text = 'Reset', command = self.reset)
        reset.grid(column = 3, row = 0, **self.paddingArgs)

        login_frame = LabelFrame(top, borderwidth = 2, relief = 'groove', text = 'Session information')
        login_frame.grid(column = 0, row = 1, sticky = W + E + N + S,
                         padx = 2, pady = 2)

        self.login.set(1)

        login_switch = Checkbutton(login_frame, text = 'Login required?',
                                   variable = self.login)
        login_switch.grid(column = 0, row = 0, columnspan = 2, **self.paddingArgs)

        self.user.set('foo')
        self.password.set('bar')

        user_text = Label(login_frame, text = 'Username:'******'Password:'******'groove', text = 'Service information')
        info_frame.grid(column = 1, row = 1, sticky = W + E + N + S, **self.paddingArgs)

        self.info_text = Label(info_frame, text = 'Please press "GO"')
        self.info_text.pack(side = 'top')

        test_frame = LabelFrame(top, borderwidth = 2, relief = 'groove', text = 'Tests')
        test_frame.grid(column = 0, row = 2, columnspan = 2, **self.paddingArgs)

        label = Label(test_frame, text = 'Checking for correct version information:')
        label.grid(column = 0, row = 0, sticky = W, **self.paddingArgs)

        self.version_test_label = Label(test_frame, text = '...')
        self.version_test_label.grid(column = 1, row = 0, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Checking completeness of infrastructure model:')
        label.grid(column = 0, row = 1, sticky = W, **self.paddingArgs)

        self.infra_model_test_label = Label(test_frame, text = '...')
        self.infra_model_test_label.grid(column = 1, row = 1, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Checking correct handling of Content-type/Accept headers:')
        label.grid(column = 0, row = 2, sticky = W, **self.paddingArgs)

        self.accept_header_test_label = Label(test_frame, text = '...')
        self.accept_header_test_label.grid(column = 1, row = 2, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Testing instantiation of compute/storage/network kinds:')
        label.grid(column = 0, row = 3, sticky = W, **self.paddingArgs)

        self.creational_test_label = Label(test_frame, text = '...')
        self.creational_test_label.grid(column = 1, row = 3, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Testing correct handling of user-defined mixins (tagging/grouping):')
        label.grid(column = 0, row = 4, sticky = W, **self.paddingArgs)

        self.mixin_test_label = Label(test_frame, text = '...')
        self.mixin_test_label.grid(column = 1, row = 4, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Testing links between compute/storage compute/network:')
        label.grid(column = 0, row = 5, sticky = W, **self.paddingArgs)

        self.link_test_label = Label(test_frame, text = '...')
        self.link_test_label.grid(column = 1, row = 5, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Triggering actions on compute/network/storage kinds:')
        label.grid(column = 0, row = 6, sticky = W, **self.paddingArgs)

        self.action_test_label = Label(test_frame, text = '...')
        self.action_test_label.grid(column = 1, row = 6, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Testing filter mechanisms using Categories:')
        label.grid(column = 0, row = 7, sticky = W, **self.paddingArgs)

        self.filter_test_label = Label(test_frame, text = '...')
        self.filter_test_label.grid(column = 1, row = 7, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Testing correct behaviour on location and "normal" paths:')
        label.grid(column = 0, row = 8, sticky = W, **self.paddingArgs)

        self.location_path_label = Label(test_frame, text = '...')
        self.location_path_label.grid(column = 1, row = 8, sticky = W, **self.paddingArgs)

        label = Label(test_frame, text = 'Simple syntax checks:')
        label.grid(column = 0, row = 9, sticky = W, **self.paddingArgs)

        self.syntax_test_label = Label(test_frame, text = '...')
        self.syntax_test_label.grid(column = 1, row = 9, sticky = W, **self.paddingArgs)

        label = Label(top, text = 'NOTE: Passing all tests only indicates that the service\nyou are testing is OCCI compliant - IT DOES NOT GUARANTE IT!')
        label.grid(column = 0, row = 4, columnspan = 2, **self.paddingArgs)

        quit_button = Button(top, text = 'Quit', command = self.quit)
        quit_button.grid(column = 1, row = 5, sticky = E, **self.paddingArgs)

    def run_tests(self):
        '''
        run a set of tests.
        '''
        url = self.url.get()
        if self.login.get() is 1:
            cookie = test_occi.get_session_cookie(self.url.get(), self.user.get(),
                                        self.password.get())
            heads = {'Cookie': cookie}
        else:
            heads = {}

        # display basic information
        self.info_text.configure(text = 'Server version:\n'
                                    + test_occi.get_version(url, heads)
                                    + '\nNumber of registered categories:\n'
                                    + str(len(test_occi.get_categories(url, heads))),
                                    anchor = W, justify = LEFT)

        # run the tests...
        self.run_single_test(test_occi.test_version_information, url, heads, self.version_test_label)
        self.run_single_test(test_occi.test_infrastructure_model_for_completness, url, heads, self.infra_model_test_label)
        self.run_single_test(test_occi.test_accept_header, url, heads, self.accept_header_test_label)
        self.run_single_test(test_occi.test_create_kinds, url, heads, self.creational_test_label)
        self.run_single_test(test_occi.test_mixins, url, heads, self.mixin_test_label)
        self.run_single_test(test_occi.test_links, url, heads, self.link_test_label)
        self.run_single_test(test_occi.test_actions, url, heads, self.action_test_label)
        self.run_single_test(test_occi.test_filter, url, heads, self.filter_test_label)
        self.run_single_test(test_occi.test_location, url, heads, self.location_path_label)
        self.run_single_test(test_occi.test_syntax, url, heads, self.syntax_test_label)

    def run_single_test(self, test, url, heads, label):
        '''
        Run a single test and display the outcome.
        '''
        try:
            test(url, heads)
        except Exception as ae:
            logging.warn(str(ae))
            label.configure(text = 'Failed', background = 'red')
        else:
            label.configure(text = 'OK')

    def reset(self):
        '''
        Reset the gui...
        '''
        self.info_text.configure(text = 'Please press "GO"')
        self.version_test_label.configure(text = '...')
        self.infra_model_test_label.configure(text = '...')
        self.accept_header_test_label.configure(text = '...')
        self.creational_test_label.configure(text = '...')
        self.mixin_test_label.configure(text = '...')
        self.link_test_label.configure(text = '...')
        self.action_test_label.configure(text = '...')
        self.filter_test_label.configure(text = '...')
        self.location_path_label.configure(text = '...')
        self.syntax_test_label.configure(text = '...')

    def quit(self):
        '''
        Quit the master loop.
        '''
        self.master.quit()
Example #52
0
class Game:
    def __init__(self):
        self.root = Tk()
        self.frame1 = None
        self.frame2 = None
        self.w = None
        self.scoreC = None
        self.score = 0
        self.hor = True
        self.upid = self.downid = self.rightid = self.leftid = 0
        self.head = -1
        self.time = 700

    def home(self):
        self.frame1 = Frame(self.root, width=750, height=350, padx=250, bg="black")
        self.frame2 = Frame(self.root, height=250, width=750, bg="black", padx=25)
        self.root.wm_minsize(width=750, height=666)
        self.root.configure(bg="black")
        self.frame1.pack_propagate(0)
        self.frame1.update()
        self.frame1.configure(pady=self.frame1.cget("height") / 2.5)
        logo = PhotoImage(file="Game_Logo.gif")
        starth = Button(self.frame1, text="Hard", bg="orange", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(40))
        startm = Button(self.frame1, text="Medium", bg="teal", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(60))
        starte = Button(self.frame1, text="Easy", bg="orange", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(75))
        self.frame2.pack_propagate(0)
        exp = """        This is a game in which
        the arrow keys are used
        to move the snake around
        and to get points"""
        exf = Font(family="comic sans MS", size=20)
        Label(self.frame2, image=logo, bg="black", text=exp, padx=10).pack(side="right")
        Label(self.frame2, fg="white", bg="black", text=exp, justify="left", font=exf).pack(side="left")
        starte.grid(row=0, columnspan=2)
        startm.grid(row=0, columnspan=2, column=4, padx=18)
        starth.grid(row=0, columnspan=2, column=8)
        head = Font(family="comic sans MS", size=30)
        self.H=Label(self.root, text="SNAKES", font=head, fg="orange", bg="black", pady=10)
        self.H.pack()
        self.frame2.pack(expand=True)
        self.frame1.pack(expand=True)
        self.root.mainloop()

    def callgame(self, time):
        self.time = time
        self.game()

    def calldown(self, key):
        if self.hor:
            self.w.after_cancel(self.leftid)
            self.w.after_cancel(self.rightid)
            self.down(0)

    def callup(self, key):
        if self.hor:
            self.w.after_cancel(self.leftid)
            self.w.after_cancel(self.rightid)
            self.up(0)

    def callright(self, key):
        if not self.hor:
            self.w.after_cancel(self.upid)
            self.w.after_cancel(self.downid)
            self.right(0)

    def callleft(self, key):
        if not self.hor:
            self.w.after_cancel(self.upid)
            self.w.after_cancel(self.downid)
            self.left(0)

    def game(self):
        self.score = 0
        self.w = Canvas(self.root, width=750, height=500, relief="flat", highlightbackground="grey",
                        highlightthickness=10)
        self.frame1.destroy()
        self.frame2.destroy()
        self.root.configure(width=1000, padx=10)
        self.root.pack_propagate(0)
        self.w.configure(background="black")
        self.w.pack(side="left")
        self.w.create_line(300, 250, 450, 250, width=10, fill="teal")
        self.scoreC = Label(self.root, text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35,
                            font=Font(family="comic sans MS", size=25))
        self.head = self.w.create_line(450, 250, 455, 250, width=10, fill="white")
        self.scoreC.pack(side="top")
        self.root.bind("<Up>", self.callup)
        self.root.bind("<Down>", self.calldown)
        self.root.bind("<Right>", self.callright)
        self.root.bind("<Left>", self.callleft)
        self.createFood()
        self.right(0)

    def down(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] + 5, width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.downid = self.w.after(self.time, self.down, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def up(self, i):
        crd = self.w.coords(1)
        if len(crd)>0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] - 5, width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.upid = self.w.after(self.time, self.up, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def right(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] + 5, crd[-1], width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.rightid = self.w.after(self.time, self.right, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def left(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] - 5, crd[-1], width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.leftid = self.w.after(self.time, self.left, i)
            else:

                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def createFood(self):
        # self.w.delete(self.food) #deleting old food.
        crd = self.w.coords(1)
        ext = []
        for i in crd:
            ext.append(i)
            for j in range(-50, 50):
                ext.append(i + j)
        randx = random.randrange(20, 730)
        randy = random.randrange(20, 480)
        while randx not in ext and randy not in ext:
            randx = random.randrange(20, 730)
            randy = random.randrange(20, 480)
        self.food = self.w.create_line(randx, randy, randx + 12, randy, width=10, fill="yellow")

    def checkEaten(self):
        headcoords = self.w.coords(self.head)
        foodcoords = self.w.coords(self.food)
        # self.w.delete(self.food)
        flag = False
        # print(headcoords[-4])
        # print(foodcoords[-4])
        # print(foodcoords[-2])
        if int(headcoords[-4]) in range(int(foodcoords[-4]) - 7, int(foodcoords[-2]) + 7) and int(
                headcoords[-3]) in range(int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)):
            flag = True
        if flag:
            self.grow()
            self.score += 10
            self.scoreC.configure(text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35,
                                  font=Font(family="comic sans MS", size=25))
            self.w.delete(self.food)
            self.createFood()

    def grow(self):
        crd = self.w.coords(1)
        if crd[0] != crd[2]:  # horizontal condition
            if crd[0] < crd[2]:
                crd[0] -= 20
            else:
                crd[0] += 20
            self.w.coords(1, *crd)
        else:
            if crd[3] < crd[1]:
                crd[1] += 20
            else:
                crd[1] -= 20
            self.w.coords(1, *crd)

    def end(self):
        crd = self.w.coords(1)
        h = self.w.coords(self.head)
        a = 0
        while a < len(crd) - 2:
            if crd[a] == crd[a + 2]:
                if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or (
                        h[0] == crd[a]  and crd[a + 1] > h[1] > crd[a + 3]):
                    return True
            else:
                if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or (h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]):
                    return True
            a += 2
        if (h[0] == 0 and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or (h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760 and 0<h[1]<500):
            return True
        return False


    def callhome(self):
        self.w.destroy()
        self.start.destroy()
        self.H.destroy()
        self.scoreC.destroy()
        self.home()
class path_planner_gui(StoppableThread):
    DEFAULT_START_LAT = 55.434352  #55.43526 #55.431122
    DEFAULT_START_LON = 10.415182  #10.41086 #10.420436
    DEFAULT_GOAL_LAT = 55.42474  #55.427203
    DEFAULT_GOAL_LON = 10.41975  #10.419043

    # for testing altitude - points near Hindsgavl, Middelfart
    # start_point_3dDICT = {'lat': 55.505618, 'lon': 9.681612, 'alt_rel': 0}
    # goal_point_3dDICT  = {'lat': 55.518093, 'lon': 9.699519, 'alt_rel': 0}
    # goal inside geofence: 55.429331, 10.422770

    DEFAULT_STEP_SIZE_HORZ_ASTAR = 100
    DEFAULT_STEP_SIZE_VERT_ASTAR = 10
    DEFAULT_STEP_SIZE_HORZ_RRT = 50
    DEFAULT_STEP_SIZE_VERT_RRT = 10
    DEFAULT_SEARCH_TIME_MAX = 120  # unit: s
    DEFAULT_ITERATIONS_MAX = 3000

    DEFAULT_TIME_STEP = 1.0  # unit: s
    DEFAULT_ACCELERATION_FACTOR = 10.0  # unitless

    DEFAULT_STEP_SIZE_HORZ_LOCAL_ASTAR = 50
    DEFAULT_STEP_SIZE_VERT_LOCAL_ASTAR = 5
    DEFAULT_SEARCH_TIME_MAX_LOCAL = 180  # unit: s

    DEFAULT_STEP_SIZE_HORZ_LOCAL_RRT = 25
    DEFAULT_STEP_SIZE_VERT_LOCAL_RRT = 5
    DEFAULT_ITERATIONS_MAX_LOCAL = 3000  # unit: s

    INITIAL_PLANNER = 1

    def __init__(self, parent_class, auto_start=False):
        # self.__class__ = type(self.__class__.__name__, (base_class, object), dict(self.__class__.__dict__))
        # super(self.__class__, self).__init__()
        self.parent_class = parent_class

        StoppableThread.__init__(self)
        self.q = Queue()

        self.logger = logging.getLogger(__name__)
        if auto_start:
            self.start()

    def stop_thread(self):
        self.callback_close()
        self.stop()

    def callback_close(self):
        self.root.quit()
        self.logger.info(
            'Tkinter GUI has stopped but thread will first be joined upon closing of the program'
        )

    def on_main_thread(self, func):
        self.q.put(func)

    def check_queue(self):
        while True:
            try:
                task = self.q.get(block=False)
            except Empty:
                break
            else:
                self.root.after_idle(task)
        self.root.after(100, self.check_queue)

    def set_label_no_fly_zones(self, txt, color='black'):
        self.label_data_source_no_fly_zones_res.configure(text=txt)
        self.label_data_source_no_fly_zones_res.configure(fg=color)

    def set_label_height_map(self, txt, color='black'):
        self.label_data_source_height_map_res.configure(text=txt)
        self.label_data_source_height_map_res.configure(fg=color)

    def set_label_drone_id(self, txt, color='black'):
        self.label_data_source_droneID_res.configure(text=txt)
        self.label_data_source_droneID_res.configure(fg=color)

    def set_label_adsb(self, txt, color='black'):
        self.label_data_source_adsb_res.configure(text=txt)
        self.label_data_source_adsb_res.configure(fg=color)

    def set_label_weather(self, txt, color='black'):
        self.label_data_source_weather_res.configure(text=txt)
        self.label_data_source_weather_res.configure(fg=color)

    def set_label_rally_points(self, txt, color='black'):
        self.label_data_rally_point_res.configure(text=txt)
        self.label_data_rally_point_res.configure(fg=color)

    def set_global_plan_start_heuristic(self, val, color='black'):
        self.label_global_plan_start_heuristic_res.configure(text='%.02f' %
                                                             val)
        self.label_global_plan_start_heuristic_res.configure(fg=color)

    def set_global_plan_cur_heuristic(self, val, color='black'):
        self.label_global_plan_cur_heuristic_res.configure(text='%.02f' % val)
        self.label_global_plan_cur_heuristic_res.configure(fg=color)

    def set_global_plan_horz_step_size(self, val, color='black'):
        self.label_global_plan_horz_step_size_res.configure(text='%.01f [m]' %
                                                            val)
        self.label_global_plan_horz_step_size_res.configure(fg=color)

    def set_global_plan_vert_step_size(self, val, color='black'):
        self.label_global_plan_vert_step_size_res.configure(text='%.01f [m]' %
                                                            val)
        self.label_global_plan_vert_step_size_res.configure(fg=color)

    def set_global_plan_status(self, txt, color='black'):
        self.label_global_plan_status_res.configure(text=txt)
        self.label_global_plan_status_res.configure(fg=color)

    def set_global_plan_search_time(self, val, color='black'):
        self.label_global_plan_search_time_res.configure(text='%.01f [s]' %
                                                         val)
        self.label_global_plan_search_time_res.configure(fg=color)

    def set_global_plan_nodes_visited(self, val, color='black'):
        self.label_global_plan_nodes_visited_res.configure(text='%i' % val)
        self.label_global_plan_nodes_visited_res.configure(fg=color)

    def set_global_plan_nodes_explored(self, val, color='black'):
        self.label_global_plan_nodes_explored_res.configure(text='%i' % val)
        self.label_global_plan_nodes_explored_res.configure(fg=color)

    def set_label_gpe_fitness(self, val, color='black'):
        self.label_gpe_fitness_res.configure(text='%f' % val)
        self.label_gpe_fitness_res.configure(fg=color)

    def set_label_gpe_dist_tot(self, val, color='black'):
        self.label_gpe_dist_tot_res.configure(text='%.02f [m]' % val)
        self.label_gpe_dist_tot_res.configure(fg=color)

    def set_label_gpe_dist_horz(self, val, color='black'):
        self.label_gpe_dist_horz_res.configure(text='%.02f [m]' % val)
        self.label_gpe_dist_horz_res.configure(fg=color)

    def set_label_gpe_dist_vert(self, val, color='black'):
        self.label_gpe_dist_vert_res.configure(text='%.02f [m]' % val)
        self.label_gpe_dist_vert_res.configure(fg=color)

    def set_label_gpe_eta(self, val, color='black'):
        self.label_gpe_eta_res.configure(text='%.02f [s]' % val)
        self.label_gpe_eta_res.configure(fg=color)

    def set_label_gpe_wps(self, val, color='black'):
        self.label_gpe_wps_res.configure(text='%i' % val)
        self.label_gpe_wps_res.configure(fg=color)

    def set_label_gpe_runtime(self, val, color='black'):
        self.label_gpe_runtime_res.configure(text='%.02f [s]' % val)
        self.label_gpe_runtime_res.configure(fg=color)

    def set_label_gpe_bytes_tot(self, val, color='black'):
        self.label_gpe_bytes_tot_res.configure(text='%i' % val)
        self.label_gpe_bytes_tot_res.configure(fg=color)

    def set_label_gpe_objects_tot(self, val, color='black'):
        self.label_gpe_objects_tot_res.configure(text='%i' % val)
        self.label_gpe_objects_tot_res.configure(fg=color)

    def set_label_gpe_bytes_planner(self, val, color='black'):
        self.label_gpe_bytes_planner_res.configure(text='%i' % val)
        self.label_gpe_bytes_planner_res.configure(fg=color)

    def set_label_gpe_objects_planner(self, val, color='black'):
        self.label_gpe_objects_planner_res.configure(text='%i' % val)
        self.label_gpe_objects_planner_res.configure(fg=color)

    def set_scrolledtext_global_path(self, txt):
        self.scrolledtext_global_path.delete(1.0, END)
        self.scrolledtext_global_path.insert(INSERT, txt)

    def set_scrolledtext_local_path(self, txt):
        self.scrolledtext_local_path.delete(1.0, END)
        self.scrolledtext_local_path.insert(INSERT, txt)

    def enable_button_global_plan(self):
        self.button_global_plan.configure(state='normal')

    def diable_button_global_plan(self):
        self.button_global_plan.configure(state='disabled')

    def set_label_local_plan_status(self, txt, color='black'):
        self.label_local_plan_status_res.configure(text=txt)
        self.label_local_plan_status_res.configure(fg=color)

    def set_label_local_plan_time(self, val, color='black'):
        self.label_local_plan_time_res.configure(text='%.02f [s]' % val)
        self.label_local_plan_time_res.configure(fg=color)

    def set_label_local_uav_y(self, val, color='black'):
        self.label_local_uav_y_res.configure(text='%.01f [m]' % val)
        self.label_local_uav_y_res.configure(fg=color)

    def set_label_local_uav_x(self, val, color='black'):
        self.label_local_uav_x_res.configure(text='%.01f [m]' % val)
        self.label_local_uav_x_res.configure(fg=color)

    def set_label_local_uav_z_rel(self, val, color='black'):
        self.label_local_uav_z_rel_res.configure(text='%.01f [m]' % val)
        self.label_local_uav_z_rel_res.configure(fg=color)

    def set_label_local_uav_status(self, txt, color='black'):
        self.label_local_uav_status_res.configure(text=txt)
        self.label_local_uav_status_res.configure(fg=color)

    def global_planner_thread(self, point_start, point_goal, path_planner,
                              step_size_horz, step_size_vert, search_time_max):
        if self.parent_class.plan_path_global(
                point_start,
                point_goal,
                path_planner,
                step_size_horz=step_size_horz,
                step_size_vert=step_size_vert,
                search_time_max=search_time_max
        ):  # Plan path and test the result to update the GUI
            self.button_local_plan.configure(state='normal')
            self.button_global_plan.configure(state='normal')
            self.button_gen_global_sim_files.configure(state='normal')
            self.button_global_plan.configure(text='Start global planning')
            self.button_show_result_webpage_global.configure(state='normal')
            self.button_evaluate_path.configure(state='normal')
            self.button_web_visualize_global.configure(state='normal')
        else:  # The global path planner failed and therefore diable the local path planner and change the option to continue
            self.button_local_plan.configure(state='disabled')
            self.button_global_plan.configure(state='normal')
            self.button_gen_global_sim_files.configure(state='disabled')
            self.button_show_result_webpage_global.configure(state='disabled')
            path_planner = str(self.combo_planner_type.get())
            if path_planner == self.parent_class.PATH_PLANNER_NAMES[0]:
                self.button_global_plan.configure(
                    text='Continue global planning')
            elif path_planner == self.parent_class.PATH_PLANNER_NAMES[1]:
                self.button_global_plan.configure(text='Retry global planning')
            self.button_evaluate_path.configure(state='disabled')
            self.button_web_visualize_global.configure(state='disabled')

    def start_global_path_planning(self):
        self.button_global_plan.configure(state='disabled')
        self.button_gen_global_sim_files.configure(state='disabled')
        self.button_local_plan.configure(state='disabled')
        self.button_show_result_webpage_global.configure(state='disabled')
        self.button_evaluate_path.configure(state='disabled')
        self.button_web_visualize_global.configure(state='disabled')

        # Get data from the GUI
        path_planner = self.combo_planner_type.get()
        start_point_3dDICT = {
            'lat': float(self.input_start_point_lat.get()),
            'lon': float(self.input_start_point_lon.get()),
            'alt_rel': 0
        }
        goal_point_3dDICT = {
            'lat': float(self.input_goal_point_lat.get()),
            'lon': float(self.input_goal_point_lon.get()),
            'alt_rel': 0
        }
        step_size_horz = float(self.input_step_size_horz.get())
        step_size_vert = float(self.input_step_size_vert.get())
        search_time_max = float(self.input_search_time_max.get())

        # Create and start the thread
        thread_global_planning = threading.Thread(
            target=self.global_planner_thread,
            args=(start_point_3dDICT, goal_point_3dDICT, path_planner,
                  step_size_horz, step_size_vert, search_time_max))
        thread_global_planning.start()
        #thread_global_planning.join()

    def local_planner_thread(self, path_planner, step_size_horz,
                             step_size_vert, max_search_time, time_step,
                             acceleration_factor):
        self.parent_class.plan_path_local(
            path_planner=path_planner,
            step_size_horz=step_size_horz,
            step_size_vert=step_size_vert,
            max_search_time=max_search_time,
            time_step=time_step,
            acceleration_factor=acceleration_factor)
        self.button_global_plan.configure(state='normal')
        self.button_gen_global_sim_files.configure(state='normal')
        self.button_local_plan.configure(state='normal')
        self.button_web_visualize_local.configure(state='normal')
        self.button_show_result_webpage_local.configure(state='normal')
        self.button_gen_local_sim_files.configure(state='normal')

    def start_local_path_planning(self):
        self.button_global_plan.configure(state='disabled')
        self.button_gen_global_sim_files.configure(state='disabled')
        self.button_local_plan.configure(state='disabled')
        self.button_web_visualize_local.configure(state='disabled')
        self.button_show_result_webpage_local.configure(state='disabled')
        self.button_gen_local_sim_files.configure(state='disabled')
        # Get data from the GUI
        path_planner = str(self.combo_planner_type.get())
        time_step = float(self.input_time_step.get())
        acceleration_factor = float(self.input_acceleration_factor.get())
        step_size_horz = float(self.input_replan_step_size_horz.get())
        step_size_vert = float(self.input_replan_step_size_vert.get())
        search_time_max = float(self.input_replan_search_time_max.get())
        # Create and start the thread
        thread_local_planning = threading.Thread(
            target=self.local_planner_thread,
            args=(path_planner, step_size_horz, step_size_vert,
                  search_time_max, time_step, acceleration_factor))
        thread_local_planning.start()

    def show_result_webpage_global_thread(self):
        self.parent_class.draw_planned_path_global()
        self.parent_class.map_plotter_global.show_plot()

    def show_result_webpage_global(self):
        show_result_webpage_global = threading.Thread(
            target=self.show_result_webpage_global_thread)
        show_result_webpage_global.start()

    def gen_global_sim_files_thread(self):
        self.parent_class.generate_simulation_files_global()

    def gen_global_sim_files(self):
        gen_global_sim = threading.Thread(
            target=self.gen_global_sim_files_thread)
        gen_global_sim.start()

    def gen_local_sim_files_thread(self):
        self.parent_class.generate_simulation_files_local()

    def gen_local_sim_files(self):
        gen_local_sim = threading.Thread(
            target=self.gen_local_sim_files_thread)
        gen_local_sim.start()

    def show_result_webpage_local_thread(self):
        self.parent_class.draw_planned_path_local()
        self.parent_class.map_plotter_local.show_plot()

    def show_result_webpage_local(self):
        show_result_webpage_local = threading.Thread(
            target=self.show_result_webpage_local_thread)
        show_result_webpage_local.start()

    def show_web_visualize_global(self):
        route_id = self.parent_class.visualize_path_3d_global()
        if not None:
            url = 'http://uas.heltner.net/routes/' + str(route_id) + '/3d'
            webbrowser.open_new(url)

    def show_web_visualize_local(self):
        route_id = self.parent_class.visualize_path_3d_local()
        if not None:
            url = 'http://uas.heltner.net/routes/' + str(route_id) + '/3d'
            webbrowser.open_new(url)

    def path_evaluation_thread(self):
        self.parent_class.evaluate_path()

    def start_evaluation(self):
        # Create and start the thread
        thread_evaluate_path = threading.Thread(
            target=self.path_evaluation_thread)
        thread_evaluate_path.start()

    def change_planner(self, event=None):
        path_planner = str(self.combo_planner_type.get())
        if path_planner == self.parent_class.PATH_PLANNER_NAMES[0]:
            self.input_step_size_horz.delete(0, END)
            self.input_step_size_horz.insert(0,
                                             self.DEFAULT_STEP_SIZE_HORZ_ASTAR)
            self.input_step_size_vert.delete(0, END)
            self.input_step_size_vert.insert(0,
                                             self.DEFAULT_STEP_SIZE_VERT_ASTAR)
            self.label_search_time_max.configure(text='Max search time [s]:')
            self.input_search_time_max.delete(0, END)
            self.input_search_time_max.insert(0, self.DEFAULT_SEARCH_TIME_MAX)
            self.input_replan_step_size_horz.delete(0, END)
            self.input_replan_step_size_horz.insert(
                0, self.DEFAULT_STEP_SIZE_HORZ_LOCAL_ASTAR)
            self.input_replan_step_size_vert.delete(0, END)
            self.input_replan_step_size_vert.insert(
                0, self.DEFAULT_STEP_SIZE_VERT_LOCAL_ASTAR)
            self.label_replan_search_time_max.configure(
                text='Replan max search time [s]:')
            self.input_replan_search_time_max.delete(0, END)
            self.input_replan_search_time_max.insert(
                0, self.DEFAULT_SEARCH_TIME_MAX_LOCAL)
        elif path_planner == self.parent_class.PATH_PLANNER_NAMES[1]:
            self.input_step_size_horz.delete(0, END)
            self.input_step_size_horz.insert(0,
                                             self.DEFAULT_STEP_SIZE_HORZ_RRT)
            self.input_step_size_vert.delete(0, END)
            self.input_step_size_vert.insert(0,
                                             self.DEFAULT_STEP_SIZE_VERT_RRT)
            self.label_search_time_max.configure(text='Max iterations:')
            self.input_search_time_max.delete(0, END)
            self.input_search_time_max.insert(0, self.DEFAULT_ITERATIONS_MAX)
            self.input_replan_step_size_horz.delete(0, END)
            self.input_replan_step_size_horz.insert(
                0, self.DEFAULT_STEP_SIZE_HORZ_LOCAL_RRT)
            self.input_replan_step_size_vert.delete(0, END)
            self.input_replan_step_size_vert.insert(
                0, self.DEFAULT_STEP_SIZE_VERT_LOCAL_RRT)
            self.label_replan_search_time_max.configure(
                text='Replan max iterations:')
            self.input_replan_search_time_max.delete(0, END)
            self.input_replan_search_time_max.insert(
                0, self.DEFAULT_ITERATIONS_MAX_LOCAL)

    def run(self):
        self.root = Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback_close)
        self.root.title("UAV Path Planner")
        #self.root.geometry('{}x{}'.format(460, 350))
        """ Left side layout """
        row_num_left = 0
        self.label_start_point = Label(self.root,
                                       text="Path Planning",
                                       font=("Arial Bold", 12))
        self.label_start_point.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_planner_type = Label(self.root, text="Type:")
        self.label_planner_type.grid(row=row_num_left, column=0)
        self.combo_planner_type = Combobox(self.root)
        self.combo_planner_type[
            'values'] = self.parent_class.PATH_PLANNER_NAMES
        if self.INITIAL_PLANNER == 0:
            self.combo_planner_type.current(0)
        elif self.INITIAL_PLANNER == 1:
            self.combo_planner_type.current(1)
        self.combo_planner_type.bind('<<ComboboxSelected>>',
                                     self.change_planner)
        self.combo_planner_type.grid(row=row_num_left, column=1)

        row_num_left += 1
        self.label_start_point = Label(self.root,
                                       text="Start point (geodetic)",
                                       font=("Arial Bold", 10))
        self.label_start_point.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_start_point_lat = Label(self.root, text="Latitude [dd]:")
        self.label_start_point_lat.grid(row=row_num_left, column=0)
        self.input_start_point_lat = Entry(self.root, width=10)
        self.input_start_point_lat.insert(0, self.DEFAULT_START_LAT)
        self.input_start_point_lat.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_start_point_lon = Label(self.root, text="Longitude [dd]:")
        self.label_start_point_lon.grid(row=row_num_left, column=0)
        self.input_start_point_lon = Entry(self.root, width=10)
        self.input_start_point_lon.insert(0, self.DEFAULT_START_LON)
        self.input_start_point_lon.grid(row=row_num_left, column=1)

        row_num_left += 1
        self.label_goal_point = Label(self.root,
                                      text="Goal point (geodetic)",
                                      font=("Arial Bold", 10))
        self.label_goal_point.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_goal_point_lat = Label(self.root, text="Latitude [dd]:")
        self.label_goal_point_lat.grid(row=row_num_left, column=0)
        self.input_goal_point_lat = Entry(self.root, width=10)
        self.input_goal_point_lat.insert(0, self.DEFAULT_GOAL_LAT)
        self.input_goal_point_lat.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_goal_point_lon = Label(self.root, text="Longitude [dd]:")
        self.label_goal_point_lon.grid(row=row_num_left, column=0)
        self.input_goal_point_lon = Entry(self.root, width=10)
        self.input_goal_point_lon.insert(0, self.DEFAULT_GOAL_LON)
        self.input_goal_point_lon.grid(row=row_num_left, column=1)

        row_num_left += 1
        self.label_options = Label(self.root,
                                   text="Options global path planner",
                                   font=("Arial Bold", 10))
        self.label_options.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_step_size_horz = Label(self.root,
                                          text="Horizontal step-size [m]:")
        self.label_step_size_horz.grid(row=row_num_left, column=0)
        self.input_step_size_horz = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_step_size_horz.insert(0,
                                             self.DEFAULT_STEP_SIZE_HORZ_ASTAR)
        elif self.INITIAL_PLANNER == 1:
            self.input_step_size_horz.insert(0,
                                             self.DEFAULT_STEP_SIZE_HORZ_RRT)
        self.input_step_size_horz.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_step_size_vert = Label(self.root,
                                          text="Vertical step-size [m]:")
        self.label_step_size_vert.grid(row=row_num_left, column=0)
        self.input_step_size_vert = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_step_size_vert.insert(0,
                                             self.DEFAULT_STEP_SIZE_VERT_ASTAR)
        elif self.INITIAL_PLANNER == 1:
            self.input_step_size_vert.insert(0,
                                             self.DEFAULT_STEP_SIZE_VERT_RRT)
        self.input_step_size_vert.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_search_time_max = Label(self.root, text="")
        if self.INITIAL_PLANNER == 0:
            self.label_search_time_max.configure(text='Max search time [s]:')
        elif self.INITIAL_PLANNER == 1:
            self.label_search_time_max.configure(text='Max iterations:')
        self.label_search_time_max.grid(row=row_num_left, column=0)
        self.input_search_time_max = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_search_time_max.insert(0, self.DEFAULT_SEARCH_TIME_MAX)
        elif self.INITIAL_PLANNER == 1:
            self.input_search_time_max.insert(0, self.DEFAULT_ITERATIONS_MAX)
        self.input_search_time_max.grid(row=row_num_left, column=1)

        row_num_left += 1
        self.button_global_plan = Button(
            self.root,
            text="Start global planning",
            command=self.start_global_path_planning)
        self.button_global_plan.configure(state='disabled')
        self.button_global_plan.grid(row=row_num_left, column=0, columnspan=2)

        row_num_left += 1
        self.label_options_local = Label(self.root,
                                         text="Options local path planner",
                                         font=("Arial Bold", 10))
        self.label_options_local.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_time_step = Label(self.root, text="Time step [s]:")
        self.label_time_step.grid(row=row_num_left, column=0)
        self.input_time_step = Entry(self.root, width=10)
        self.input_time_step.insert(0, self.DEFAULT_TIME_STEP)
        self.input_time_step.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_acceleration_factor = Label(self.root,
                                               text="Playback speed:")
        self.label_acceleration_factor.grid(row=row_num_left, column=0)
        self.input_acceleration_factor = Entry(self.root, width=10)
        self.input_acceleration_factor.insert(0,
                                              self.DEFAULT_ACCELERATION_FACTOR)
        self.input_acceleration_factor.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_replan_step_size_horz = Label(
            self.root, text="Replan horizontal step-size [m]:")
        self.label_replan_step_size_horz.grid(row=row_num_left, column=0)
        self.input_replan_step_size_horz = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_replan_step_size_horz.insert(
                0, self.DEFAULT_STEP_SIZE_HORZ_LOCAL_ASTAR)
        elif self.INITIAL_PLANNER == 1:
            self.input_replan_step_size_horz.insert(
                0, self.DEFAULT_STEP_SIZE_HORZ_LOCAL_RRT)
        self.input_replan_step_size_horz.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_replan_step_size_vert = Label(
            self.root, text="Replan vertical step-size [m]:")
        self.label_replan_step_size_vert.grid(row=row_num_left, column=0)
        self.input_replan_step_size_vert = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_replan_step_size_vert.insert(
                0, self.DEFAULT_STEP_SIZE_VERT_LOCAL_ASTAR)
        elif self.INITIAL_PLANNER == 1:
            self.input_replan_step_size_vert.insert(
                0, self.DEFAULT_STEP_SIZE_VERT_LOCAL_RRT)
        self.input_replan_step_size_vert.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_replan_search_time_max = Label(
            self.root, text="Replan max search time [s]:")
        if self.INITIAL_PLANNER == 0:
            self.label_replan_search_time_max.configure(
                text='Replan max search time [s]:')
        elif self.INITIAL_PLANNER == 1:
            self.label_replan_search_time_max.configure(
                text='Replan max iterations:')
        self.label_replan_search_time_max.grid(row=row_num_left, column=0)
        self.input_replan_search_time_max = Entry(self.root, width=10)
        if self.INITIAL_PLANNER == 0:
            self.input_replan_search_time_max.insert(
                0, self.DEFAULT_SEARCH_TIME_MAX_LOCAL)
        elif self.INITIAL_PLANNER == 1:
            self.input_replan_search_time_max.insert(
                0, self.DEFAULT_ITERATIONS_MAX_LOCAL)
        self.input_replan_search_time_max.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.button_local_plan = Button(self.root,
                                        text="Start local planning",
                                        command=self.start_local_path_planning)
        self.button_local_plan.configure(
            state='disabled'
        )  # disable the button since it cannot make a local plan before it has made a global plan
        self.button_local_plan.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_sim_info = Label(self.root,
                                    text="Simulation information",
                                    font=("Arial Bold", 12))
        self.label_sim_info.grid(row=row_num_left, column=0, columnspan=2)
        row_num_left += 1
        self.label_local_plan_status = Label(self.root, text="Status:")
        self.label_local_plan_status.grid(row=row_num_left, column=0)
        self.label_local_plan_status_res = Label(self.root, text="idle")
        self.label_local_plan_status_res.configure(fg='green')
        self.label_local_plan_status_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_plan_time = Label(self.root, text="Time:")
        self.label_local_plan_time.grid(row=row_num_left, column=0)
        self.label_local_plan_time_res = Label(self.root, text="N/A")
        self.label_local_plan_time_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_uav_y = Label(self.root, text="UAV y:")
        self.label_local_uav_y.grid(row=row_num_left, column=0)
        self.label_local_uav_y_res = Label(self.root, text="N/A")
        self.label_local_uav_y_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_uav_x = Label(self.root, text="UAV x:")
        self.label_local_uav_x.grid(row=row_num_left, column=0)
        self.label_local_uav_x_res = Label(self.root, text="N/A")
        self.label_local_uav_x_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_uav_z_rel = Label(self.root, text="UAV z_rel:")
        self.label_local_uav_z_rel.grid(row=row_num_left, column=0)
        self.label_local_uav_z_rel_res = Label(self.root, text="N/A")
        self.label_local_uav_z_rel_res.grid(row=row_num_left, column=1)
        row_num_left += 1
        self.label_local_uav_status = Label(self.root, text="UAV status:")
        self.label_local_uav_status.grid(row=row_num_left, column=0)
        self.label_local_uav_status_res = Label(self.root, text="N/A")
        self.label_local_uav_status_res.grid(row=row_num_left, column=1)
        """ Right side layout """
        row_num_right = 0
        self.label_data_sources = Label(self.root,
                                        text="Data sources",
                                        font=("Arial Bold", 12))
        self.label_data_sources.grid(row=row_num_right, column=2, columnspan=2)
        row_num_right += 1
        self.label_data_source_no_fly_zones = Label(self.root,
                                                    text="No-fly zones:")
        self.label_data_source_no_fly_zones.grid(row=row_num_right, column=2)
        self.label_data_source_no_fly_zones_res = Label(self.root,
                                                        text="not loaded")
        self.label_data_source_no_fly_zones_res.configure(fg='red')
        self.label_data_source_no_fly_zones_res.grid(row=row_num_right,
                                                     column=3)
        row_num_right += 1
        self.label_data_source_height_map = Label(self.root,
                                                  text="Altitude map:")
        self.label_data_source_height_map.grid(row=row_num_right, column=2)
        self.label_data_source_height_map_res = Label(self.root,
                                                      text="not loaded")
        self.label_data_source_height_map_res.configure(fg='red')
        self.label_data_source_height_map_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_data_source_droneID = Label(self.root, text="DroneID:")
        self.label_data_source_droneID.grid(row=row_num_right, column=2)
        self.label_data_source_droneID_res = Label(self.root,
                                                   text="not loaded")
        self.label_data_source_droneID_res.configure(fg='red')
        self.label_data_source_droneID_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_data_source_adsb = Label(self.root, text="ADS-B:")
        self.label_data_source_adsb.grid(row=row_num_right, column=2)
        self.label_data_source_adsb_res = Label(self.root, text="not loaded")
        self.label_data_source_adsb_res.configure(fg='red')
        self.label_data_source_adsb_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_data_source_weather = Label(self.root, text="Weather:")
        self.label_data_source_weather.grid(row=row_num_right, column=2)
        self.label_data_source_weather_res = Label(self.root,
                                                   text="not loaded")
        self.label_data_source_weather_res.configure(fg='red')
        self.label_data_source_weather_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_data_rally_point = Label(self.root, text="Rally points:")
        self.label_data_rally_point.grid(row=row_num_right, column=2)
        self.label_data_rally_point_res = Label(self.root, text="not loaded")
        self.label_data_rally_point_res.configure(fg='red')
        self.label_data_rally_point_res.grid(row=row_num_right, column=3)

        row_num_right += 1
        # gpe = global path evaluator
        self.label_gpe = Label(self.root,
                               text="Global path evaluator",
                               font=("Arial Bold", 12))
        self.label_gpe.grid(row=row_num_right, column=2, columnspan=2)
        row_num_right += 1
        self.button_evaluate_path = Button(self.root,
                                           text="Evaluate",
                                           command=self.start_evaluation)
        self.button_evaluate_path.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_evaluate_path.grid(row=row_num_right,
                                       column=2,
                                       columnspan=2)
        row_num_right += 1
        self.label_gpe_fitness = Label(self.root, text="Fitness:")
        self.label_gpe_fitness.grid(row=row_num_right, column=2)
        self.label_gpe_fitness_res = Label(self.root, text="N/A")
        self.label_gpe_fitness_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_dist_tot = Label(self.root, text="Total distance:")
        self.label_gpe_dist_tot.grid(row=row_num_right, column=2)
        self.label_gpe_dist_tot_res = Label(self.root, text="N/A")
        self.label_gpe_dist_tot_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_dist_horz = Label(self.root,
                                         text="Horizontal distance:")
        self.label_gpe_dist_horz.grid(row=row_num_right, column=2)
        self.label_gpe_dist_horz_res = Label(self.root, text="N/A")
        self.label_gpe_dist_horz_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_dist_vert = Label(self.root, text="Vertical distance:")
        self.label_gpe_dist_vert.grid(row=row_num_right, column=2)
        self.label_gpe_dist_vert_res = Label(self.root, text="N/A")
        self.label_gpe_dist_vert_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_eta = Label(self.root, text="Estimated flight time:")
        self.label_gpe_eta.grid(row=row_num_right, column=2)
        self.label_gpe_eta_res = Label(self.root, text="N/A")
        self.label_gpe_eta_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_wps = Label(self.root, text="Waypoints:")
        self.label_gpe_wps.grid(row=row_num_right, column=2)
        self.label_gpe_wps_res = Label(self.root, text="N/A")
        self.label_gpe_wps_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_runtime = Label(self.root, text="Runtime:")
        self.label_gpe_runtime.grid(row=row_num_right, column=2)
        self.label_gpe_runtime_res = Label(self.root, text="N/A")
        self.label_gpe_runtime_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_bytes_tot = Label(self.root, text="Bytes total:")
        self.label_gpe_bytes_tot.grid(row=row_num_right, column=2)
        self.label_gpe_bytes_tot_res = Label(self.root, text="N/A")
        self.label_gpe_bytes_tot_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_objects_tot = Label(self.root, text="Objects total:")
        self.label_gpe_objects_tot.grid(row=row_num_right, column=2)
        self.label_gpe_objects_tot_res = Label(self.root, text="N/A")
        self.label_gpe_objects_tot_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_bytes_planner = Label(self.root, text="Bytes planner:")
        self.label_gpe_bytes_planner.grid(row=row_num_right, column=2)
        self.label_gpe_bytes_planner_res = Label(self.root, text="N/A")
        self.label_gpe_bytes_planner_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_gpe_objects_planner = Label(self.root,
                                               text="Objects planner:")
        self.label_gpe_objects_planner.grid(row=row_num_right, column=2)
        self.label_gpe_objects_planner_res = Label(self.root, text="N/A")
        self.label_gpe_objects_planner_res.grid(row=row_num_right, column=3)

        row_num_right += 1
        self.label_planning_info = Label(self.root,
                                         text="Planning information",
                                         font=("Arial Bold", 12))
        self.label_planning_info.grid(row=row_num_right,
                                      column=2,
                                      columnspan=2)
        row_num_right += 1
        self.label_global_plan_status = Label(self.root, text="Status:")
        self.label_global_plan_status.grid(row=row_num_right, column=2)
        self.label_global_plan_status_res = Label(self.root, text="idle")
        self.label_global_plan_status_res.configure(fg='green')
        self.label_global_plan_status_res.grid(row=row_num_right, column=3)
        row_num_right += 1
        self.label_global_plan_start_heuristic = Label(self.root,
                                                       text="Start heuristic:")
        self.label_global_plan_start_heuristic.grid(row=row_num_right,
                                                    column=2)
        self.label_global_plan_start_heuristic_res = Label(self.root,
                                                           text="N/A")
        self.label_global_plan_start_heuristic_res.grid(row=row_num_right,
                                                        column=3)
        row_num_right += 1
        self.label_global_plan_cur_heuristic = Label(self.root,
                                                     text="Best heuristic:")
        self.label_global_plan_cur_heuristic.grid(row=row_num_right, column=2)
        self.label_global_plan_cur_heuristic_res = Label(self.root, text="N/A")
        self.label_global_plan_cur_heuristic_res.grid(row=row_num_right,
                                                      column=3)
        row_num_right += 1
        self.label_global_plan_horz_step_size = Label(
            self.root, text="Horizontal step-size:")
        self.label_global_plan_horz_step_size.grid(row=row_num_right, column=2)
        self.label_global_plan_horz_step_size_res = Label(self.root,
                                                          text="N/A")
        self.label_global_plan_horz_step_size_res.grid(row=row_num_right,
                                                       column=3)
        row_num_right += 1
        self.label_global_plan_vert_step_size = Label(
            self.root, text="Vertical step-size:")
        self.label_global_plan_vert_step_size.grid(row=row_num_right, column=2)
        self.label_global_plan_vert_step_size_res = Label(self.root,
                                                          text="N/A")
        self.label_global_plan_vert_step_size_res.grid(row=row_num_right,
                                                       column=3)
        row_num_right += 1
        self.label_global_plan_search_time = Label(self.root,
                                                   text="Search time:")
        self.label_global_plan_search_time.grid(row=row_num_right, column=2)
        self.label_global_plan_search_time_res = Label(self.root, text="N/A")
        self.label_global_plan_search_time_res.grid(row=row_num_right,
                                                    column=3)
        row_num_right += 1
        self.label_global_plan_nodes_visited = Label(self.root,
                                                     text="Nodes visited:")
        self.label_global_plan_nodes_visited.grid(row=row_num_right, column=2)
        self.label_global_plan_nodes_visited_res = Label(self.root, text="N/A")
        self.label_global_plan_nodes_visited_res.grid(row=row_num_right,
                                                      column=3)
        row_num_right += 1
        self.label_global_plan_nodes_explored = Label(self.root,
                                                      text="Nodes explored:")
        self.label_global_plan_nodes_explored.grid(row=row_num_right, column=2)
        self.label_global_plan_nodes_explored_res = Label(self.root,
                                                          text="N/A")
        self.label_global_plan_nodes_explored_res.grid(row=row_num_right,
                                                       column=3)
        """ Both sides """
        if row_num_left > row_num_right:
            row_num_both = row_num_left
        else:
            row_num_both = row_num_right
        row_num_both += 1
        self.label_global_path = Label(self.root, text="Global path:")
        self.label_global_path.grid(row=row_num_both, column=0)
        self.scrolledtext_global_path = tkst.ScrolledText(self.root, height=5)
        self.scrolledtext_global_path.grid(row=row_num_both,
                                           column=1,
                                           columnspan=3)

        row_num_both += 1
        self.label_local_path = Label(self.root, text="Local path:")
        self.label_local_path.grid(row=row_num_both, column=0)
        self.scrolledtext_local_path = tkst.ScrolledText(self.root, height=5)
        self.scrolledtext_local_path.grid(row=row_num_both,
                                          column=1,
                                          columnspan=3)

        row_num_both += 1
        self.button_show_result_webpage_global = Button(
            self.root,
            text="2D global path visualization (local)",
            command=self.show_result_webpage_global)
        self.button_show_result_webpage_global.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_show_result_webpage_global.grid(row=row_num_both,
                                                    column=0,
                                                    columnspan=2)
        #row_num_both += 1
        self.button_show_result_webpage_local = Button(
            self.root,
            text="2D local path visualization (local)",
            command=self.show_result_webpage_local)
        self.button_show_result_webpage_local.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_show_result_webpage_local.grid(row=row_num_both,
                                                   column=2,
                                                   columnspan=2)

        row_num_both += 1
        self.button_web_visualize_global = Button(
            self.root,
            text="3D global path visualization (online)",
            command=self.show_web_visualize_global)
        self.button_web_visualize_global.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_web_visualize_global.grid(row=row_num_both,
                                              column=0,
                                              columnspan=2)
        #row_num_both += 1
        self.button_web_visualize_local = Button(
            self.root,
            text="3D local path visualization (online)",
            command=self.show_web_visualize_local)
        self.button_web_visualize_local.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_web_visualize_local.grid(row=row_num_both,
                                             column=2,
                                             columnspan=2)

        row_num_both += 1
        self.button_gen_global_sim_files = Button(
            self.root,
            text="Generate global path simulation files",
            command=self.gen_global_sim_files)
        self.button_gen_global_sim_files.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_gen_global_sim_files.grid(row=row_num_both,
                                              column=0,
                                              columnspan=2)
        #row_num_both += 1
        self.button_gen_local_sim_files = Button(
            self.root,
            text="Generate local path simulation files",
            command=self.gen_local_sim_files)
        self.button_gen_local_sim_files.configure(
            state='disabled')  # Disabled because no global plan has been made
        self.button_gen_local_sim_files.grid(row=row_num_both,
                                             column=2,
                                             columnspan=2)

        row_num_both += 1
        self.label_credit = Label(
            self.root,
            text="Copyright (c) 2018, Tobias Lundby, BSD 3-Clause License",
            fg="grey",
            font=("Arial 8 italic"))
        self.label_credit.grid(row=row_num_both, column=0, columnspan=4)

        # Configure the queue callback
        self.root.after(250, self.check_queue)

        # Start the main loop
        self.root.mainloop()
Example #54
0
class WindowExample(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.result = 0
        self.master.title("This is a test")
        self.master.minsize(width=600, height=800)
        #self.master.

        self.prompt = Label(self,
                            text="Enter a number:",
                            anchor="w",
                            fg="#984301")
        self.entry = Entry(self, width=50, highlightcolor="red")
        self.submit = Button(self, text="Submit", command=self.calculate)
        self.exit = Button(self, text="Exit", command=parent.destroy, fg="red")
        self.output = Label(self, text="")
        self.menu = Menu(self, title="Menu test", bg="black")
        self.canvas = Canvas(self,
                             cursor="circle",
                             highlightcolor="blue",
                             bg="#019bf0")

        self.button1 = Button(self, text = "tast antum", bg = "red", fg = "green", command = self.newWindow, \
              activebackground = "red", activeforeground = "blue", relief = "sunken", cursor = "dot")

        self.newFrame = Frame(self, bg="green", highlightcolor="blue")
        self.button2 = Button(self.newFrame, text="This is a tast")
        self.button2.grid()
        self.scale = Scale(self,
                           from_=50,
                           to_=60,
                           orient="horizontal",
                           digits=3,
                           resolution=0.25,
                           highlightcolor="red",
                           command=self.calculate)
        self.scale.pack()
        self.open_file_button = Button(self,
                                       text="Open File",
                                       command=self.openFile)

        self.prompt.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x")
        self.output.pack(side="top", fill="x", expand=True)
        self.submit.pack(side="right")
        self.exit.pack(side="left")
        self.button1.pack(fill="x")
        self.newFrame.pack(side="bottom", fill="x", expand=True)
        self.button2.grid()
        self.canvas.pack()
        self.open_file_button.pack()
        #self.slider.pack()

        #self.tk = Tkinter.Tk()
        #self.tk.withdrow()
        #self.file_path = Tkinter.filedialog.askopenfilename()
        #print("test")
        self.entry.insert(string="3", index=0)
        #self.entry.insert(string = "blahblah", index = 3)

    def calculate(self, integer):
        integer = float(integer)
        #try:
        #	i = int(self.entry.get())
        #	self.result = "%s*2=%s" % (i, i*2)
        #except ValueError:
        #	self.result = "Please enter numbers only"
        self.entry.delete(0, len(self.entry.get()))
        self.result = "%s*2=%s" % (integer, integer * 2)
        self.entry.insert(0, integer)

        self.output.configure(text=self.result)

    def newWindow(self):
        try:
            r2 = Tk()
            r2.mainloop()
        except ValueError:
            return None

    def openFile(self):
        file_in = tkFileDialog.askopenfilename()
        self.output.configure(text=file_in)
Example #55
0
class PodSearch(object):
    '''This is the GUI class'''

    # Initialization of variables
    filename = ""

    # Initialization of GUI
    def __init__(self, master):
        '''Init of the GUI'''
        # Frame for progress bar
        self.bottomframe = Frame(master,
                                 highlightbackground="green",
                                 highlightcolor="green",
                                 highlightthickness=1,
                                 width=500,
                                 height=200)
        self.bottomframe.pack(side=BOTTOM)

        # Frame for buttons and entry
        self.leftframe = Frame(master,
                               highlightbackground="blue",
                               highlightcolor="blue",
                               highlightthickness=1,
                               width=400,
                               height=400)
        self.leftframe.pack(side=LEFT)

        # Sub frame  for buttons
        self.leftsubframe_top = Frame(self.leftframe,
                                      highlightbackground="yellow",
                                      highlightcolor="yellow",
                                      highlightthickness=1)
        self.leftsubframe_top.pack(side=TOP)

        # Sub frame for entry
        self.leftsubframe_bot = Frame(self.leftframe,
                                      highlightbackground="purple",
                                      highlightcolor="purple",
                                      highlightthickness=1)
        self.leftsubframe_bot.pack(side=BOTTOM)

        # Frame for wordcloud
        rightframe = Frame(master,
                           highlightbackground="red",
                           highlightcolor="red",
                           highlightthickness=1,
                           width=250,
                           height=250)
        rightframe.pack(side=RIGHT)

        # Browse button
        self.browsebtn = Button(self.leftsubframe_top,
                                text="Browse",
                                command=self.browse)
        self.browsebtn.pack(side=LEFT)

        # Quit button
        self.quitbtn = Button(self.leftsubframe_top,
                              text="Quit",
                              command=self.leftframe.quit)
        self.quitbtn.pack(side=LEFT)

        # Filepath label
        self.pathlabel = Label(self.leftsubframe_bot, text="filename")
        self.pathlabel.pack()

        # Textbox
        self.searchentry = Entry(self.leftsubframe_bot)
        self.searchentry.pack()
        self.searchentry.bind('<Return>', lambda _: self.search())

        # Search button
        self.searchbtn = Button(self.leftsubframe_bot,
                                text="Search",
                                command=self.search)
        self.searchbtn.pack()

        # Word label
        self.wordlabel = Label(self.bottomframe)
        self.wordlabel.pack()

        # Timestamp label
        self.timestamplabel = Label(self.bottomframe)
        self.timestamplabel.pack()

        # estimate label
        self.estimatelabel = Label(self.bottomframe)
        self.estimatelabel.pack()

        # Working Label
        self.workinglabel = Label(self.bottomframe)
        self.workinglabel.pack()

        # Progress Bar
        self.pbar_det = ttk.Progressbar(self.bottomframe,
                                        orient="horizontal",
                                        length=400,
                                        mode="indeterminate")

        # Wordcloud preparation
        self.imagefile = "wordcloudTools/black_background.png"
        self.imagefile = Image.open(self.imagefile)
        self.image1 = self.imagefile.resize((400, 400), Image.ANTIALIAS)
        self.image1 = ImageTk.PhotoImage(self.image1)

        self.panel1 = Label(rightframe, image=self.image1)
        self.display = self.image1
        self.panel1.pack(side=TOP, fill=BOTH, expand=YES)

        # Non GUI initializations
        self.duration = 0
        self.transcription = ""
        self.stemmed = ""
        self.transcription = ""
        self.imagefile2 = 0
        self.image2 = 0

    # Browse function
    def browse(self):
        '''browse for file'''
        if self.wordlabel != "":  # clear the labels if necessary
            self.wordlabel.config(text="")
            self.pathlabel.config(text="")
            self.timestamplabel.config(text="")
            self.estimatelabel.config(text="")
        self.filename = askopenfilename(
        )  # openfile dialog and put file in filename
        if not self.filename:  # leave method if cancel is clicked
            return
        self.pathlabel.config(text=basename(
            self.filename))  # show filename as label
        if self.filename.endswith('.txt'):
            return
        self.workinglabel.config(text="WORKING",
                                 font=("Helvetica",
                                       20))  # Show WORKING when transcribing
        self.pbar_det.pack()  # show the progress bar
        self.pbar_det.start()  # Start the progress bar
        root.update()
        self.transcription = transcribe(self.filename)  # Call transcribe

        wordcloud_path = wordcloud_create(self.transcription)
        self.transcription = removerlap(self.transcription.split(' '))
        self.new_image(wordcloud_path)

        self.workinglabel.config(text="")  # remove working label
        self.pbar_det.stop()  # Stop progress bar
        self.pbar_det.pack_forget()  # Remove progress bar

    # Search function
    def search(self):
        '''Search using text domain'''
        if not self.transcription == '':
            if not self.searchentry.get() == '':
                keyword = self.searchentry.get()  # Get entry from textbox

                # *********************************************************************************
                # Here coes code
                # *********************************************************************************

                # Write result to label
                if wordlabel != "Word number":
                    self.wordlabel.config(text=wordlabel)
                    self.estimatelabel.config(text=time)
                    self.timestamplabel.config(text=timestamplabel)
                else:
                    self.wordlabel.config(text="Word not found")
                    self.timestamplabel.config(text="")
                    self.estimatelabel.config(text="")
            else:
                self.wordlabel.config(text="Enter word in search field")
        else:
            self.timestamplabel.config(text="No file selected")

    def new_image(self, path):
        '''Word Cloud image'''
        self.imagefile2 = Image.open(path)
        self.image2 = self.imagefile2.resize((400, 400), Image.ANTIALIAS)
        self.image2 = ImageTk.PhotoImage(self.image2)
        self.panel1.configure(image=self.image2)
        self.display = self.image2
Example #56
0
class ListEditor(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        border_width = 1
        border_style = SUNKEN
        background_colour = "#FFFFFF"
        default_height = 600

        nav_frame = Frame(
            self, height=default_height, width=200, bd=border_width, relief=border_style, bg=background_colour
        )

        content_frame = Frame(self, height=default_height, width=804, bd=border_width, relief=border_style)
        content_frame.parent = parent

        nav_frame.grid(column=0, row=0)
        content_frame.grid(column=1, row=0)
        nav_frame.grid_propagate(0)
        content_frame.pack_propagate(0)

        # Create fonts for navLabels
        fontMouseOver = tkFont.Font(family="Helvetica", size=14, underline=True)
        fontMouseOut = tkFont.Font(family="Helvetica", size=14, underline=False)

        # Creating Navigation Labels
        self.lNavStudentRecords = Label(
            nav_frame,
            text="Student Records",
            bg="white",
            font=fontMouseOut,
            bd=border_width,
            relief=border_style,
            width=20,
        )
        self.lNavViewLists = Label(
            nav_frame,
            text="View Word Lists",
            bg="white",
            font=fontMouseOut,
            bd=border_width,
            relief=border_style,
            width=20,
        )

        self.lNavCreateLists = Label(
            nav_frame,
            text="Create Word Lists",
            bg="white",
            font=fontMouseOut,
            bd=border_width,
            relief=border_style,
            width=20,
        )

        buttonBack = Button(nav_frame, text="Back", command=self.parent.new_list)

        # Binding Mouse events to the Labels
        # Mouse Clicks
        self.lNavViewLists.bind("<Button-1>", partial(self.switch_frame, 2))
        self.lNavCreateLists.bind("<Button-1>", partial(self.switch_frame, 1))
        self.lNavStudentRecords.bind("<Button-1>", partial(self.switch_frame, 3))
        # Mouse Movements
        self.lNavViewLists.bind("<Enter>", lambda (event): self.lNavViewLists.configure(font=fontMouseOver))
        self.lNavCreateLists.bind("<Enter>", lambda (event): self.lNavCreateLists.configure(font=fontMouseOver))
        self.lNavViewLists.bind("<Leave>", lambda (event): self.lNavViewLists.configure(font=fontMouseOut))
        self.lNavCreateLists.bind("<Leave>", lambda (event): self.lNavCreateLists.configure(font=fontMouseOut))
        self.lNavStudentRecords.bind("<Enter>", lambda (event): self.lNavStudentRecords.configure(font=fontMouseOver))
        self.lNavStudentRecords.bind("<Leave>", lambda (event): self.lNavStudentRecords.configure(font=fontMouseOut))
        # Gridding the labels
        # self.lNavStudentRecords.grid(column=0, row=0)
        self.lNavViewLists.grid(column=0, row=1)
        self.lNavCreateLists.grid(column=0, row=2)
        buttonBack.grid(column=0, row=3)

        # Creating the two views we have so far
        self.viewcreate = CreateView(content_frame, default_height, 800, border_style, border_width, background_colour)

        self.viewlists = ListView(content_frame, default_height, 800, border_style, border_width, background_colour)
        self.viewlists.pack()

    def switch_frame(self, frameNumber, event):
        if frameNumber == 1:
            self.viewlists.pack_forget()
            self.viewcreate.pack()
            self.lNavViewLists.configure(bg="white", fg="black")
            self.lNavCreateLists.configure(bg="#DDDDDD", fg="#8800AA")
            self.lNavStudentRecords.configure(bg="white", fg="black")
            self.viewcreate.update_category()
        elif frameNumber == 2:
            self.viewcreate.pack_forget()
            self.viewlists.pack()
            self.lNavCreateLists.configure(bg="white", fg="black")
            self.lNavViewLists.configure(bg="#DDDDDD", fg="#8800AA")
            self.lNavStudentRecords.configure(bg="white", fg="black")
            self.viewlists.update()
        else:
            self.viewcreate.pack_forget()
            self.viewlists.pack_forget()
            self.lNavCreateLists.configure(bg="white", fg="black")
            self.lNavViewLists.configure(bg="white", fg="black")
            self.lNavStudentRecords.configure(bg="#DDDDDD", fg="#8800AA")
Example #57
0
class Palette_frame(Frame):
    def __init__(self,
                 master,
                 text=None,
                 borderwidth=2,
                 width=0,
                 height=16,
                 interior_padx=0,
                 interior_pady=8,
                 background=None,
                 caption_separation=4,
                 caption_font=None,
                 caption_builder=None,
                 icon_x=5):
        Frame.__init__(self, master)

        self._is_opened = False

        self._interior_padx = interior_padx
        self._interior_pady = interior_pady

        self._iconOpen = PhotoImage(
            data=
            "R0lGODlhEwATAPcAAAAAAAAAAQD/AAIAAQUAAgcFAAoEAAwHABALABQMBBUPARUSAhUTBhgQBBgVCRsUACEWACIcACYgACggACshACwoADElATEpADEtATQkADQpADYxBDctATk0AT8uAEA6AEE1AEU0AUY3AEY7AUc/Ako7AUpFBUxAA1BHAVE6AFRHAFU/AFdGAFdQAFhCAFlUAVpMAFxGAF1DAF5TAGBaAGNIAGRYAGReAmVSAGhMAGpPAGpWAmpfAm1SAG9RAHFXAHFhAXFrAXJbAXJnAHZuA3dYAHxcAnxfAXxkAHxuAH1gAH5qAX5zAIBcAoRiAIRxAIR5AIdmAIhqAIlyAImAAop6AIxmAI9xAY95AY+BAJJtAJRvAJSIAJV5AZWAAJd1AJl0App5AJtxAZuJAJx/AJyKAZyPAJ+UAKB2AKGAAKKIAaSUAKV7AKeAAaeJAKqeA6uQAKuaAKyVAa+BAK+JALCiALOEALORALSWALSiALWaALeqAbmLALuhALyXALyqALywAL6LAMC0AMGfAMGkAMKRAMOWAMOpAMOvAMO6AMqYAMqiAMqyAMunAMuuAMu+AMy5AM2dAs7DANGfAtG7AdKwANPFANWoANXFANihANi4ANi9ANmyANnEANrLANunAN6mAN/MAOC/AODFAOK5AOLRAOOsAOWxAOasAOfFAefWAOm5AenNAOnTAOu/AOyzBezaAO3YAO60Be7dAPDFAPG1APLQAPO9APPLAPPdAPPjAfS2APTBAPTDAPW/APa/APbAAPbDAPbXAPe/APfIAPfPAPi9APjLAPjjAPm9APnXAPnbAPnkAPrRAPrqAPu8APu/APvBAPvDAPvNAPvUAPvXAPvdAPviAPzHAPzLAPzTAfzWAPzdAPzhAPzkAPzlAPzuAP2+AP3MAP3PAP3VAP3ZAP3iAP3kAP3pAP3sAP3tAP3vAP68AP7FAP7IAP7KAP7RAP7TAf7XAP7aAP7dAP7fAP7jAP7lAP7oAP7qAP7xAP/GAP/pAP/uAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFBwACACwAAAAAEwATAAAIuAABCBxIsKDBgwgFRuBhpqHDLCYSjtiTq6LFVmM0aNyoIUKBEoSaiRzZbBSiPyj/EOrzZEKIQr5+AZsJLNgydThzqktEosShZcusCRV6L5/Ro/kSmTjB6J7Tp1CjIiLB1JzVq1izTj3hiJ7Xr2DDHqLaSJ7Zs2jRljtUokSjeHDjyp1LqO2icXjz6t07yK67v4ADC+5bwlC0w4gTKzYkwsMcU5AjS548xwMCDzkya97M2XLCz6ARBgQAIfkEBQYAAgAsAAACABMAEAAAAg+Uj6nL7Q+jnLTai7PeHBUAIfkEBQcAAgAsAAACABIACgAAAgyUj6nL7Q+jnLTaVgAAIfkEBQcAAgAsAwAFAAUAAgAAAgOUjwUAOw=="
        )
        self._iconClose = PhotoImage(
            data=
            "R0lGODlhEwATAPcAAAAAAAAAAgD/AAEAAAEBAAIAAQUEAAoFAAsJAA4LABMOABUSBRcPAhkUABoYBx4XBB8YACEbASQfASgiACoeAC4jAS4nADEsADMvATQnADUuBTYuADk2ATsxADwtAT84AUI7AEQzAEQ5AEZBAEo5Ako9AUpDAU88AVBGAVBLAVQ9AVRCAFZQAVhGAFhLAVtUAV9CAF9LAWFQAmFZAWFaAGJRAGRLAWVHAGVeAGdiAGtTAmtZBGxZAGxkAG1PAG1iAnFdAHFpAXRUAnRWA3RZAXRiAXZeAHhqAXpiAXpvAXtzAYBcAIFrAYJjAoNgAYN1AoV9AYhrAop0AYtlAI2FAY59AY9jAJB4AJFrApFsApJyAZOFAZRoAZSMAZV+AJmCAJuPAJxmAJxzAJ15AJ2IAJ+CAKGQAaGXAaV6AKV7AKeLAKh8AKiRAKmXAatpAqyhAK2BAK+IAbGEALGYALKEBbOlArV6AbWIALaaAbiLALiUArihArqtAb2NAL+uAMCQA8CZAMGkAMGoAMOAAMO1AcWuAMaTAMa7AMeZAcuYA8uZAMunAMy1AM2YAM29Ac6wAM+bANLFAtSeANSoAdS3AdW+AdaCANahAdfMAdmIANqmAN2wAd3EAN3NAt6oAN7BAOCTAOC4AeHWAeKJAOOsAOSaAOStAOXJAOaMAOeQAOqTAOrQAOuyAOu9AOvKAOvWAOvfAuyWAO2gAO6oAO+bAO+2AO+4APGvAPG8APKfAPLeAPPPAPSiAPSoAPS7APTFAPTXAPW1APW4APXAAPXlAPbKAPemAPerAPfOAPfgAPfqAPjVAPjaAPmwAPm8APm/APnMAPq1APq5APrHAPrgAPvCAPvOAPvXAPvrAfzUAPzgAPzmAPztAPzvAP27AP3AAP3FAP3HAP3KAP3MAP3VAP3ZAP3iAP3kAP3qAP3vAP7FAP7IAP7JAP7MAP7PAP7SAP7TAP7XAP7YAP7cAf7eAP7fAP7jAP7nAP7qAP7sAP7uAP/QAP/TAP/bAP/oAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFBwACACwAAAAAEwATAAAIygABCBxIsKDBgwgHGlCwoGFDBQcSAugQRImSJ0+UBPkgEQosYiBB6jojgkRJkx0aCNyyDZ/Ll6sEBZo5c44MgVWuzdvJsyfPZVUEaoHWrqjRduOSjitaTIpALMGkSZ0aTZgwZ1id+dLC4IATVbFo0cpF1teys2iXVWLxotIuZHDRanv5Mh+xHj+SmdvLt6/fVS9kuPJJuOcjEyUWwVvMuLHjOR0yqFFKubLSMREUZKllq7Pnz55rRTEAgMQULKhTq07tJITE17ANBgQAIfkEBQYAAgAsAAACABMADwAACDUABQgcSLCgwYMIExoUIUKhQ4LMHkok2E7gtILRJmo8iMxhvnz4NoocqbCduJMoU6YkyVJAQAAh+QQFBwABACwBAAMAEgANAAAIHgADCBxIsKDBgwgTKlzIkKGVhhAjSpxIMaK4ihEDAgAh+QQFBwABACwCAAMAEAANAAAIIQADCBxIsKDBgwgTKlzIsOFAYQRzOUyYb6LFiwTbYWwYEAA7"
        )

        height_of_icon = max(self._iconOpen.height(), self._iconClose.height())
        width_of_icon = max(self._iconOpen.width(), self._iconClose.width())

        containerFrame_pady = (height_of_icon // 2) + 1

        self._height = height
        self._width = width

        self._containerFrame = Frame(self,
                                     borderwidth=borderwidth,
                                     width=width,
                                     height=height,
                                     relief=RIDGE,
                                     background=background)
        self._containerFrame.pack(expand=True,
                                  fill=X,
                                  pady=(containerFrame_pady, 0))

        self.interior = Frame(self._containerFrame, background=background)

        self._collapseButton = Label(self,
                                     borderwidth=0,
                                     image=self._iconOpen,
                                     relief=RAISED)
        self._collapseButton.place(in_=self._containerFrame,
                                   x=icon_x,
                                   y=-(height_of_icon // 2),
                                   anchor=N + W,
                                   bordermode="ignore")
        self._collapseButton.bind("<Button-1>", lambda event: self.toggle())

        if caption_builder is None:
            self._captionLabel = Label(self,
                                       anchor=W,
                                       borderwidth=1,
                                       text=text)
            if caption_font is not None:
                self._captionLabel.configure(font=caption_font)
        else:
            self._captionLabel = caption_builder(self)

            if not isinstance(self._captionLabel, Widget):
                raise Exception(
                    "'caption_builder' doesn't return a Tkinter widget")

        self.after(
            0, lambda: self._place_caption(caption_separation, icon_x,
                                           width_of_icon))

    def _place_caption(self, caption_separation, icon_x, width_of_icon):
        self.update()
        x = caption_separation + icon_x + width_of_icon
        y = -(self._captionLabel.winfo_reqheight() // 2)

        self._captionLabel.place(in_=self._containerFrame,
                                 x=x,
                                 y=y,
                                 anchor=N + W,
                                 bordermode="ignore")

    def open(self):
        self._collapseButton.configure(image=self._iconClose)

        self._containerFrame.configure(height=self.interior.winfo_reqheight())
        self.interior.pack(expand=True,
                           fill=X,
                           padx=self._interior_padx,
                           pady=self._interior_pady)

        self._is_opened = True

    def close(self):
        self.interior.pack_forget()
        self._containerFrame.configure(height=self._height)
        self._collapseButton.configure(image=self._iconOpen)

        self._is_opened = False

    def toggle(self):
        if self._is_opened:
            self.close()
        else:
            self.open()
Example #58
0
class SearchBox(Frame):
    def __init__(self,
                 master,
                 entry_width=30,
                 entry_font=None,
                 entry_background="white",
                 entry_highlightthickness=1,
                 button_text="Search",
                 button_ipadx=10,
                 button_background="#009688",
                 button_foreground="white",
                 button_font=None,
                 opacity=0.8,
                 placeholder=None,
                 placeholder_font=None,
                 placeholder_color="grey",
                 spacing=3,
                 command=None):
        Frame.__init__(self, master)

        self._command = command

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

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

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

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

        opacity = float(opacity)

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

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

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

        self._button_background = button_background

        self.button_label = Label(self,
                                  text=button_text,
                                  background=button_background,
                                  foreground=button_foreground,
                                  font=button_font)
        if entry_font:
            self.button_label.configure(font=button_font)

        self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx)

        self.button_label.bind("<Enter>", self._state_active)
        self.button_label.bind("<Leave>", self._state_normal)

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

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

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

        entry.delete(0, END)
        entry.insert(0, text)

    def clear(self):
        self.entry_var.set("")

    def focus(self):
        self.entry.focus()

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

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

    def _state_active(self, event):
        self.button_label.configure(background=self._button_activebackground)
Example #59
0
class TreeNode:

    def __init__(self, canvas, parent, item):
        self.canvas = canvas
        self.parent = parent
        self.item = item
        self.state = 'collapsed'
        self.selected = False
        self.children = []
        self.x = self.y = None
        self.iconimages = {} # cache of PhotoImage instances for icons

    def destroy(self):
        for c in self.children[:]:
            self.children.remove(c)
            c.destroy()
        self.parent = None

    def geticonimage(self, name):
        try:
            return self.iconimages[name]
        except KeyError:
            pass
        file, ext = os.path.splitext(name)
        ext = ext or ".gif"
        fullname = os.path.join(ICONDIR, file + ext)
        image = PhotoImage(master=self.canvas, file=fullname)
        self.iconimages[name] = image
        return image

    def select(self, event=None):
        if self.selected:
            return
        self.deselectall()
        self.selected = True
        self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselect(self, event=None):
        if not self.selected:
            return
        self.selected = False
        self.canvas.delete(self.image_id)
        self.drawicon()
        self.drawtext()

    def deselectall(self):
        if self.parent:
            self.parent.deselectall()
        else:
            self.deselecttree()

    def deselecttree(self):
        if self.selected:
            self.deselect()
        for child in self.children:
            child.deselecttree()

    def flip(self, event=None):
        if self.state == 'expanded':
            self.collapse()
        else:
            self.expand()
        self.item.OnDoubleClick()
        return "break"

    def expand(self, event=None):
        if not self.item._IsExpandable():
            return
        if self.state != 'expanded':
            self.state = 'expanded'
            self.update()
            self.view()

    def collapse(self, event=None):
        if self.state != 'collapsed':
            self.state = 'collapsed'
            self.update()

    def view(self):
        top = self.y - 2
        bottom = self.lastvisiblechild().y + 17
        height = bottom - top
        visible_top = self.canvas.canvasy(0)
        visible_height = self.canvas.winfo_height()
        visible_bottom = self.canvas.canvasy(visible_height)
        if visible_top <= top and bottom <= visible_bottom:
            return
        x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
        if top >= visible_top and height <= visible_height:
            fraction = top + height - visible_height
        else:
            fraction = top
        fraction = float(fraction) / y1
        self.canvas.yview_moveto(fraction)

    def lastvisiblechild(self):
        if self.children and self.state == 'expanded':
            return self.children[-1].lastvisiblechild()
        else:
            return self

    def update(self):
        if self.parent:
            self.parent.update()
        else:
            oldcursor = self.canvas['cursor']
            self.canvas['cursor'] = "watch"
            self.canvas.update()
            self.canvas.delete(ALL)     # XXX could be more subtle
            self.draw(7, 2)
            x0, y0, x1, y1 = self.canvas.bbox(ALL)
            self.canvas.configure(scrollregion=(0, 0, x1, y1))
            self.canvas['cursor'] = oldcursor

    def draw(self, x, y):
        # XXX This hard-codes too many geometry constants!
        dy = 20
        self.x, self.y = x, y
        self.drawicon()
        self.drawtext()
        if self.state != 'expanded':
            return y + dy
        # draw children
        if not self.children:
            sublist = self.item._GetSubList()
            if not sublist:
                # _IsExpandable() was mistaken; that's allowed
                return y+17
            for item in sublist:
                child = self.__class__(self.canvas, self, item)
                self.children.append(child)
        cx = x+20
        cy = y + dy
        cylast = 0
        for child in self.children:
            cylast = cy
            self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")
            cy = child.draw(cx, cy)
            if child.item._IsExpandable():
                if child.state == 'expanded':
                    iconname = "minusnode"
                    callback = child.collapse
                else:
                    iconname = "plusnode"
                    callback = child.expand
                image = self.geticonimage(iconname)
                id = self.canvas.create_image(x+9, cylast+7, image=image)
                # XXX This leaks bindings until canvas is deleted:
                self.canvas.tag_bind(id, "<1>", callback)
                self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
        id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,
            ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
            fill="gray50")
        self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2
        return cy

    def drawicon(self):
        if self.selected:
            imagename = (self.item.GetSelectedIconName() or
                         self.item.GetIconName() or
                         "openfolder")
        else:
            imagename = self.item.GetIconName() or "folder"
        image = self.geticonimage(imagename)
        id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
        self.image_id = id
        self.canvas.tag_bind(id, "<1>", self.select)
        self.canvas.tag_bind(id, "<Double-1>", self.flip)

    def drawtext(self):
        textx = self.x+20-1
        texty = self.y-4
        labeltext = self.item.GetLabelText()
        if labeltext:
            id = self.canvas.create_text(textx, texty, anchor="nw",
                                         text=labeltext)
            self.canvas.tag_bind(id, "<1>", self.select)
            self.canvas.tag_bind(id, "<Double-1>", self.flip)
            x0, y0, x1, y1 = self.canvas.bbox(id)
            textx = max(x1, 200) + 10
        text = self.item.GetText() or "<no text>"
        try:
            self.entry
        except AttributeError:
            pass
        else:
            self.edit_finish()
        try:
            self.label
        except AttributeError:
            # padding carefully selected (on Windows) to match Entry widget:
            self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
        theme = idleConf.CurrentTheme()
        if self.selected:
            self.label.configure(idleConf.GetHighlight(theme, 'hilite'))
        else:
            self.label.configure(idleConf.GetHighlight(theme, 'normal'))
        id = self.canvas.create_window(textx, texty,
                                       anchor="nw", window=self.label)
        self.label.bind("<1>", self.select_or_edit)
        self.label.bind("<Double-1>", self.flip)
        self.text_id = id

    def select_or_edit(self, event=None):
        if self.selected and self.item.IsEditable():
            self.edit(event)
        else:
            self.select(event)

    def edit(self, event=None):
        self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
        self.entry.insert(0, self.label['text'])
        self.entry.selection_range(0, END)
        self.entry.pack(ipadx=5)
        self.entry.focus_set()
        self.entry.bind("<Return>", self.edit_finish)
        self.entry.bind("<Escape>", self.edit_cancel)

    def edit_finish(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        text = entry.get()
        entry.destroy()
        if text and text != self.item.GetText():
            self.item.SetText(text)
        text = self.item.GetText()
        self.label['text'] = text
        self.drawtext()
        self.canvas.focus_set()

    def edit_cancel(self, event=None):
        try:
            entry = self.entry
            del self.entry
        except AttributeError:
            return
        entry.destroy()
        self.drawtext()
        self.canvas.focus_set()