Exemplo n.º 1
0
class searchDialog(Toplevel):
        def __init__(self, parent, title):
                self.top = Toplevel(parent)
                self.top.wm_title(title)
                self.top.wm_minsize(width=300, height=400)
                self.top.bind("<Return>", self.searchThreader)
                self.top.bind("<Escape>", self.close)

                self.searchy = Text(self.top)
                self.searchy.config(wrap=WORD)
                self.search_entry = Entry(self.top)
                self.close = Button(self.top, text="Close", command=self.close)
                self.search_button = Button(self.top,
                                            text="Search",
                                            command=self.searchThreader)
                self.scrollbar = Scrollbar(self.top)

                self.scrollbar.pack(side=RIGHT, fill=Y, expand=0)
                self.searchy.config(yscrollcommand=self.scrollbar.set,
                                    state=DISABLED)
                self.searchy.pack(side=TOP, fill=BOTH, expand=1)
                self.search_entry.pack(side=LEFT, fill=X, expand=1)
                self.close.pack(side=RIGHT, fill=BOTH, expand=0)
                self.search_button.pack(side=RIGHT, fill=BOTH, expand=0)

                self.linker = HyperlinkManager(self.searchy)

        def close(self, event=None):
                global SEARCH
                SEARCH = None
                self.top.destroy()

        def putText(self, text):
                updateDisplay(text, self.searchy, self.linker)

        def clearSearch(self):
                self.searchy.config(state=NORMAL)
                self.searchy.delete(1.0, END)
                self.searchy.config(state=DISABLED)

        def searchThreader(self, event=None, text=None):
                self.sear = upThread(6, 'search', (self, text))
                self.sear.start()

        def search(self, toSearch=None):
                if toSearch is None:
                        keyword = self.search_entry.get()
                        self.search_entry.delete(0, END)
                else:
                        keyword = toSearch
                self.clearSearch()
                self.top.wm_title("Search - " + keyword)
                if keyword.split('@')[0] == '':
                        self.putText(
                            API.GetUserTimeline(
                                screen_name=keyword.split('@')[1]
                            )
                        )
                else:
                        self.putText(API.GetSearch(term=keyword))
Exemplo n.º 2
0
class GUI:
    def __init__(self, title, width, height):
        from Tkinter import Tk, Canvas, Toplevel
        self.width = width
        self.height = height
        self.title = title
        self.app = Tk()
        self.app.withdraw()
        self.win = Toplevel()
        self.win.wm_title(title)
        self.canvas = Canvas(self.win,
                             width=(self.width * 2),
                             height=(self.height * 2))
        self.canvas.pack(side='bottom', expand="yes", anchor="n", fill='both')
        self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW', self.close)
        #self.canvas.bind("<Configure>", self.changeSize)

    def close(self):
        self.app.destroy()

    def draw(self, lat, length):
        print "Drawing...",
        for h in range(length):
            for w in range(self.width):
                if lat.data[h][w]:
                    self.canvas.create_rectangle(w * 2,
                                                 h * 2,
                                                 w * 2 + 2,
                                                 h * 2 + 2,
                                                 fill="black")
            self.win.update_idletasks()
        print "Done!"
Exemplo n.º 3
0
class GUI:
    def __init__(self, title, width, height):
        from Tkinter import Tk, Canvas, Toplevel
        self.width = width
        self.height = height
        self.title = title
        self.app = Tk()
        self.app.withdraw()
        self.win = Toplevel()
        self.win.wm_title(title)
        self.canvas = Canvas(self.win,
                             width=(self.width * 2),
                             height=(self.height * 2))
        self.canvas.pack(side = 'bottom', expand = "yes", anchor = "n",
                         fill = 'both')
        self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW',self.close)
        #self.canvas.bind("<Configure>", self.changeSize)
        
    def close(self):
        self.app.destroy()

    def draw(self, lat, length):
        print "Drawing...",
        for h in range(length):
            for w in range(self.width):
                if lat.data[h][w]:
                    self.canvas.create_rectangle(w*2, h*2, w*2+2, h*2+2,
                                                 fill = "black")
            self.win.update_idletasks()
        print "Done!"
Exemplo n.º 4
0
    def __init__(self,
                 rows,
                 cols,
                 width=500,
                 height=250,
                 side=25,
                 block_buffer=10,
                 title='Grid',
                 background='tan',
                 draw_fingers=False):
        assert (rows <= MAX_ROWS)
        assert (cols <= MAX_COLS)

        tk = Tk()
        tk.withdraw()
        top = Toplevel(tk)
        top.wm_title(title)
        top.protocol('WM_DELETE_WINDOW', top.destroy)

        self.width = width
        self.height = height
        self.rows = rows
        self.cols = cols
        self.canvas = Canvas(top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()
        self.side = side
        self.block_buffer = block_buffer
        self.draw_fingers = draw_fingers
        self.cells = {}
        self.robot = []
        self.draw_environment()
Exemplo n.º 5
0
def message(msg):
    global mainWin
    sub = Toplevel(mainWin)
    sub.wm_title("BonjourBackground - %s" % msg)
    lab = Label(sub, text=msg)
    lab.pack(side="top", fill="both", expand=True, padx=50, pady=20)
    pass
    def openFlipWindow(self):
        """
        open the flip window and initial all the button and text
        """
        
        panel = Toplevel(self.root)
        panel.wm_title("Gesture Recognition")

        self.btn_flipl = tki.Button(
            panel, text="Flip Left", relief="raised", command=self.telloFlip_l)
        self.btn_flipl.pack(side="bottom", fill="both",
                            expand="yes", padx=10, pady=5)

        self.btn_flipr = tki.Button(
            panel, text="Flip Right", relief="raised", command=self.telloFlip_r)
        self.btn_flipr.pack(side="bottom", fill="both",
                            expand="yes", padx=10, pady=5)

        self.btn_flipf = tki.Button(
            panel, text="Flip Forward", relief="raised", command=self.telloFlip_f)
        self.btn_flipf.pack(side="bottom", fill="both",
                            expand="yes", padx=10, pady=5)

        self.btn_flipb = tki.Button(
            panel, text="Flip Backward", relief="raised", command=self.telloFlip_b)
        self.btn_flipb.pack(side="bottom", fill="both",
                            expand="yes", padx=10, pady=5)
Exemplo n.º 7
0
def message(msg):
    global mainWin
    sub = Toplevel(mainWin)
    sub.wm_title("BonjourBackground - %s" % msg)
    lab = Label(sub, text=msg)
    lab.pack(side="top", fill="both", expand=True, padx=50, pady=20)
    pass
Exemplo n.º 8
0
def documentation(version, w, h):
    def _setdoc(evt):
        w = evt.widget
        index = int(w.curselection()[0])
        doc = w.get(index)
        textfield.config(state=NORMAL)
        textfield.delete('1.0', END)
        textfield.insert('1.0', docdic[doc])
        textfield.config(state=DISABLED)
    r = Toplevel()
    w = int(w/2)
    h = int(h/2)
    r.geometry('{}x{}+{}+{}'.format(w, h, int(w/2), int(h/2)))
    r.wm_title('Documentation accpy version {}'.format(version))

    lf = Frame(r)
    lf.pack(side=LEFT, fill=BOTH, expand=False)
    rf = Frame(r)
    rf.pack(side=RIGHT, fill=BOTH, expand=True)

    docmenuopts = ['General',
                   'Lattice editor',
                   'Citation']
    docmenu = Listbox(lf)
    for entry in docmenuopts:
        docmenu.insert(END, entry)
    docmenu.pack(fill=BOTH, expand=True)
    docmenu.bind('<<ListboxSelect>>', _setdoc)

    scrollbar = Scrollbar(orient="vertical")
    textfield = Text(rf, xscrollcommand=scrollbar.set)
    textfield.pack(fill=BOTH, expand=True)
Exemplo n.º 9
0
def about(version, w, h):
    r = Toplevel()
    r.wm_title('About')
    r.option_add('*font', 'Helvetica -16 bold')
    txt1 = Label(r, text='ACCPY version {}'.format(version))
    r.option_add('*font', 'Helvetica -14')
    txt2 = Label(r, text='Coded by\nfelix kramer\n([email protected])')
    txt1.pack()
    txt2.pack()
Exemplo n.º 10
0
 def __init__(self, width=500, height=500, title='PRM', background='tan'):
     tk = Tk()
     tk.withdraw()
     top = Toplevel(tk)
     top.wm_title(title)
     top.protocol('WM_DELETE_WINDOW', top.destroy)
     self.width = width
     self.height = height
     self.canvas = Canvas(top, width=self.width, height=self.height, background=background)
     self.canvas.pack()
Exemplo n.º 11
0
    def ventanaImprimir(self):
        t = Toplevel(self)
        t.wm_title("Imprimir")

        Label(t, text="Numero de Copias por etiqueta").pack()
        w = Spinbox(t, from_=1, to=10)
        w.pack()

        buttonImprimir = Button(t, text="Imprimir",  command=lambda:self.imprimir(int(w.get()),t))
        buttonImprimir.pack()
Exemplo n.º 12
0
 def create_window(self):
     
     t = Toplevel(self)
     t.wm_title("Elastic constants")
     l = Label(t, text="Elastic constants:")
     l.grid(row=0, column=0)
     textf = Text(t)
     try:
         textf.insert(INSERT, self.ec.get_C())
     except:
         textf.insert(INSERT, '')
     textf.grid(row=1, column=0)
Exemplo n.º 13
0
class conDialog(Toplevel):
        def __init__(self, parent, title):
                self.top = Toplevel(parent)
                self.top.wm_title(title)
                self.top.wm_minsize(width=200, height=250)

                self.parent = parent

                self.logger = Text(self.top, width=50, height=15)
                self.logger.pack(fill=BOTH, expand=1)
                self.logger.config(wrap=WORD)

                self.close = Button(self.top, text="Close",
                                    command=self.close)
                self.close.pack(fill=X, expand=0)
                self.close.focus()

                self.logger.tag_config('backlog', foreground="grey")
                self.logger.tag_config('ERR', foreground="IndianRed1")
            
                for e in range(len(ERR)):
                        if len(ERR[e][1]) > 1:
                                self.logger.insert(INSERT,
                                                   str(ERR[e][0] + "\n"),
                                                   ERR[e][1])
                        else:
                                self.logger.insert(INSERT,
                                                   str(ERR[e] + '\n'),
                                                   'backlog')
                self.logger.config(state=DISABLED)

        # destroys this Toplevel widget and sets the CON variable to None
        def close(self):
                self.top.destroy()
                global CON
                CON = None

        # method that places the text inside the log thats in the console
        #  also stores the messages in the backlog (ERR)
        def placeText(self, message):
                self.logger.config(state=NORMAL)
                ERR.append(message)
                
                if len(message[1]) > 1:
                        self.logger.insert(INSERT,
                                           str(message[0] + "\n"),
                                           message[1])
                else:
                        self.logger.insert(INSERT, message + "\n")
                
                self.logger.config(state=DISABLED)
Exemplo n.º 14
0
    def about_window(self):
        """
        Window showing information about the software and
        version number, including auto-update. If the application
        is run from a container, then auto-update is disabled
        """

        def callback(event):
            """
            open webbrowser when clicking links
            """
            webbrowser.open_new(event.widget.cget("text"))

        # main window
        t = Toplevel(self.master, width=500, height=500)
        t.wm_title("About")

        # NIC logo + name
        title = Label(t,
                      text="nicMSlesions v" + self.version + "\n"
                      "Multiple Sclerosis White Matter Lesion Segmentation")
        title.grid(row=2, column=1, padx=20, pady=10)
        img = ImageTk.PhotoImage(Image.open('./logonic.png'))
        imglabel = Label(t, image=img)
        imglabel.image = img
        imglabel.grid(row=1, column=1, padx=10, pady=10)
        group_name = Label(t,
                           text="Copyright Sergi Valverde (2018-) \n " +
                           "NeuroImage Computing Group")
        group_name.grid(row=3, column=1)
        group_link = Label(t, text=r"http://atc.udg.edu/nic",
                           fg="blue",
                           cursor="hand2")
        group_link.grid(row=4, column=1)
        group_link.bind("<Button-1>", callback)

        license_content = "Licensed under the BSD 2-Clause license. \n" + \
                          "A copy of the license is present in the root directory."

        license_label = Label(t, text=license_content)
        license_label.grid(row=5, column=1, padx=20, pady=20)

        if self.container is False:
            # check version and updates
            version_number = Label(t, text="commit: " + self.commit_version)
            version_number.grid(row=6, column=1, padx=20, pady=(1, 1))

            self.check_link = Button(t,
                                text="Check for updates",
                                command=self.check_update)
            self.check_link.grid(row=7, column=1)
Exemplo n.º 15
0
	def show_log(self, order):
		server_id = self.queue[order]['server_id'].get()
		logging.info('server_id: {0}'.format(server_id))
		t = Toplevel(self)
		
		logging.info('toplvl: {0}'.format(repr(t)))
		t.wm_title("Log for {serv}".format(serv = server_id))
		log = Text(t)
		t.protocol("WM_DELETE_WINDOW", lambda win=t, log=log: self.close_log(win, log))
		logging.info('log: {0}'.format(repr(log)))
		log.pack(side="top", fill="both", padx=10, pady=10)
		if log.winfo_exists():
			logging.info('log exists_show_log')
			self.refresh_log(log, server_id)
			logging.info('thread started')
Exemplo n.º 16
0
 def openMatches(self):
     t = Toplevel(self.master)
     t.wm_title("Current Matches")
     
     self.current_match_index = 0
     self.current_match = None
     
     button_frame = Frame(t)
     button_frame.pack()
     
     # create the "Previous Match" button
     self.prev_match_btn = Button(button_frame, text="Previous Match", fg="black", command=self.showPreviousMatch)
     self.prev_match_btn.pack(side=LEFT)
     
     # create the "Next Match" button
     self.next_match_btn = Button(button_frame, text="Next Match", fg="black", command=self.showNextMatch)
     self.next_match_btn.pack(side=LEFT)
     
     # create the "Send Message" button
     self.send_msg_btn = Button(button_frame, text="Send Message", fg="black", command=self.sendMessage)
     self.send_msg_btn.pack(side=LEFT)
     
     img_frame = Frame(t)
     img_frame.pack()
     
     # show the match
     self.match_pic = Label(img_frame)
     self.match_pic.pack(side=BOTTOM)
     
     msg_frame = Frame(t)
     msg_frame.pack()
     
     # show the previous messages
     self.match_pic = Label(img_frame)
     self.match_pic.pack(side=BOTTOM)
     
     self.msg_text = StringVar(value="")
     self.msg_lbl = Label(msg_frame, textvariable=self.msg_text)
     self.msg_lbl.pack(side=BOTTOM)
     
     text_frame = Frame(t)
     text_frame.pack()
     
     # text entry
     self.message_entry = Entry(text_frame)
     self.message_entry.pack()
     
     self.refreshMatch()
Exemplo n.º 17
0
    def nuevoPais(self):
        t = Toplevel(self)
        t.wm_title("Pais")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.grid(row=1, column=1)

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaPais(E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarPais(E2.get(), t))
        button3.config(state="disabled")

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)
Exemplo n.º 18
0
    def editarParroquia(self):
        t = Toplevel(self)
        t.wm_title("Estudio")

        Label(t, text="Nombre").grid(row=0, column=1)
        E2 = Entry(t)
        E2.insert(END, self.selectorParroquial.get())
        E2.grid(row=1, column=1)

        nombreOld = self.selectorParroquial.get()

        button1 = Button(t, text="Cancelar", command=lambda: t.destroy())
        button2 = Button(t, text="Guardar", command=lambda: self.actualizarParroquia(nombreOld, E2.get(), t))
        button3 = Button(t, text="Borrar", command=lambda: self.BorrarParroquial(E2.get(), t))

        button1.grid(row=2, column=0)
        button2.grid(row=2, column=1)
        button3.grid(row=2, column=2)
Exemplo n.º 19
0
    def create_widgets(self):
        top = Toplevel(self.root)
        top.bind("<Return>", self.default_command)
        top.bind("<Escape>", self.close)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.wm_title(self.title)
        top.wm_iconname(self.icon)
        top.resizable(height=False, width=False)
        self.ttop = top
        self.top = Frame(top)

        self.row = 0
        self.top.grid(sticky='news')

        self.create_entries()
        self.create_option_buttons()
        self.create_other_buttons()
        self.create_command_buttons()
Exemplo n.º 20
0
    def create_widgets(self):
        top = Toplevel(self.root)
        top.bind("<Return>", self.default_command)
        top.bind("<Escape>", self.close)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.wm_title(self.title)
        top.wm_iconname(self.icon)
        top.resizable(height=False, width=False)
        self.ttop = top
        self.top = Frame(top)

        self.row = 0
        self.top.grid(sticky='news')

        self.create_entries()
        self.create_option_buttons()
        self.create_other_buttons()
        self.create_command_buttons()
Exemplo n.º 21
0
class Board:
    def __init__(self, width, height, pixelsPerCell=10, title="Ants"):
        """ A board for ants to explore """
        from Tkinter import Tk, Canvas, Toplevel
        self.width = width
        self.height = height
        self.color = [
            "white", "black", "red", "yellow", "blue", "green", "purple",
            "pink", "cyan", "turquoise", "gray"
        ]
        self.board = [[0 for x in range(self.width)]
                      for y in range(self.height)]
        self.box = [[0 for x in range(self.width)] for y in range(self.height)]
        self.pixelsPerCell = pixelsPerCell
        self.title = title
        self.app = Tk()
        self.app.withdraw()
        self.win = Toplevel()
        self.win.wm_title(title)
        self.canvas = Canvas(self.win,
                             width=(self.width * pixelsPerCell),
                             height=(self.height * pixelsPerCell))
        self.canvas.pack(side='bottom', expand="yes", anchor="n", fill='both')
        self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW', self.close)
        #self.canvas.bind("<Configure>", self.changeSize)
        self.draw()

    def __getitem__(self, args):
        """ A shortcut to get a board state """
        x, y = args
        xpos, ypos = self.move(x, y)
        return self.board[xpos][ypos]

    def __setitem__(self, (x, y), value):
        """ A shortcut to assign a board state """
        xpos, ypos = self.move(x, y)
        self.canvas.itemconfig(self.box[x][y],
                               fill=self.color[value],
                               outline=self.color[value])
        self.canvas.update()
        self.board[x][y] = value
Exemplo n.º 22
0
    def __init__(self,
                 width,
                 height,
                 side=25,
                 title='Grid',
                 background='grey'):
        tk = Tk()
        tk.withdraw()
        top = Toplevel(tk)
        top.wm_title(title)
        top.protocol('WM_DELETE_WINDOW', top.destroy)

        self.width = width
        self.height = height
        self.canvas = Canvas(top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()
        self.side = side
        self.cells = {}
Exemplo n.º 23
0
    def create_widgets(self):
        '''Create basic 3 row x 3 col search (find) dialog.

        Other dialogs override subsidiary create_x methods as needed.
        Replace and Find-in-Files add another entry row.
        '''
        top = Toplevel(self.root)
        top.bind("<Return>", self.default_command)
        top.bind("<Escape>", self.close)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.wm_title(self.title)
        top.wm_iconname(self.icon)
        self.top = top

        self.row = 0
        self.top.grid_columnconfigure(0, pad=2, weight=0)
        self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100)

        self.create_entries()  # row 0 (and maybe 1), cols 0, 1
        self.create_option_buttons()  # next row, cols 0, 1
        self.create_other_buttons()  # next row, cols 0, 1
        self.create_command_buttons()  # col 2, all rows
Exemplo n.º 24
0
    def create_widgets(self):
        '''Create basic 3 row x 3 col search (find) dialog.

        Other dialogs override subsidiary create_x methods as needed.
        Replace and Find-in-Files add another entry row.
        '''
        top = Toplevel(self.root)
        top.bind("<Return>", self.default_command)
        top.bind("<Escape>", self.close)
        top.protocol("WM_DELETE_WINDOW", self.close)
        top.wm_title(self.title)
        top.wm_iconname(self.icon)
        self.top = top

        self.row = 0
        self.top.grid_columnconfigure(0, pad=2, weight=0)
        self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100)

        self.create_entries()  # row 0 (and maybe 1), cols 0, 1
        self.create_option_buttons()  # next row, cols 0, 1
        self.create_other_buttons()  # next row, cols 0, 1
        self.create_command_buttons()  # col 2, all rows
Exemplo n.º 25
0
class Board:
    def __init__(self, width, height, pixelsPerCell = 10, title = "Ants"):
        """ A board for ants to explore """
        from Tkinter import Tk, Canvas, Toplevel
        self.width = width
        self.height = height
        self.color = ["white", "black", "red", "yellow", "blue", "green", "purple", "pink", "cyan", "turquoise", "gray"]
        self.board = [[0 for x in range(self.width)] for y in range(self.height)]
        self.box = [[0 for x in range(self.width)] for y in range(self.height)]
        self.pixelsPerCell = pixelsPerCell
        self.title = title
        self.app = Tk()
        self.app.withdraw()
        self.win = Toplevel()
        self.win.wm_title(title)
        self.canvas = Canvas(self.win,
                             width=(self.width * pixelsPerCell),
                             height=(self.height * pixelsPerCell))
        self.canvas.pack(side = 'bottom', expand = "yes", anchor = "n",
                         fill = 'both')
        self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW',self.close)
        #self.canvas.bind("<Configure>", self.changeSize)
        self.draw()

    def __getitem__(self, args):
        """ A shortcut to get a board state """
        x, y = args
        xpos, ypos = self.move(x, y)
        return self.board[xpos][ypos]

    def __setitem__(self, (x, y), value):
        """ A shortcut to assign a board state """
        xpos, ypos = self.move(x, y)
        self.canvas.itemconfig(self.box[x][y], fill = self.color[value], outline = self.color[value])
        self.canvas.update()
        self.board[x][y] = value
Exemplo n.º 26
0
def settings(w, h):
    def _cancel():
        r.destroy()

    def _save():
        vallist[0] = float(entry_width.get())
        vallist[1] = float(entry_height.get())
        vallist[2] = gridon.get()
        vallist[3] = float(entry_dpi.get())
        vallist[4] = dropd_fontfamily.get()
        vallist[5] = dropd_fontsize.get()
        vallist[6] = dropd_markersize.get()
        vallist[7] = dropd_linewidth.get()
        n = dropd_laxpowerlimits.get()
        m = dropd_uaxpowerlimits.get()
        vallist[8] = [n, m]
        vallist[9] = showlat.get()
        vallist[10] = showqk.get()
        vallist[11] = showfom.get()
        vallist[12] = showqn.get()
        confsave(confpath, varlist, vallist)
        plotstandards(varlist, vallist, w, h)
        r.destroy()

    confpath = './settings.conf'
    varlist, vallist = confload(confpath)

    r = Toplevel()
    # w = int(w/2)
    # h = int(h/2)
    # r.geometry('{}x{}+{}+{}'.format(w, h, int(w/2), int(h/2)))
    r.wm_title('ACCPY Settings')

    uf = Frame(r, relief=RAISED)
    uf.pack(side=TOP, fill=BOTH, expand=True)
    lf = Frame(r)
    lf.pack(side=BOTTOM, fill=BOTH, expand=False)

    lf_figures = LabelFrame(uf, text="Figure Settings", padx=5, pady=5)
    lf_figures.grid(row=1, column=0, sticky=W+E+N+S, padx=10, pady=10)
    cs_label(lf_figures, 1, 0, 'Width / inches (25.4mm)', sticky=W)
    entry_width = cs_Dblentry(lf_figures, 2, 0, vallist[0], sticky=W+E)
    cs_label(lf_figures, 3, 0, 'Height / inches (25.4mm)', sticky=W)
    entry_height = cs_Dblentry(lf_figures, 4, 0, vallist[1], sticky=W+E)
    cs_label(lf_figures, 5, 0, 'DPI', sticky=W)
    entry_dpi = cs_Dblentry(lf_figures, 6, 0, vallist[3], sticky=W+E)
    gridon = cs_checkbox(lf_figures, 7, 0, 'Show grid', vallist[2], sticky=W)
    fontfamilys = ['serif', 'sans-serif', 'cursive', 'fantasy', 'monospace']
    cs_label(lf_figures, 8, 0, 'Fontfamily', sticky=W)
    dropd_fontfamily = cs_dropd(lf_figures, 9, 0, fontfamilys, sticky=W)
    dropd_fontfamily.set(vallist[4])
    fontsizes = range(1, 30)+range(30,80,2)
    cs_label(lf_figures, 10, 0, 'Main fontsize', sticky=W)
    dropd_fontsize = cs_dropd(lf_figures, 11, 0, fontsizes, sticky=W)
    dropd_fontsize.set(vallist[5])
    markersizes = range(1, 30)
    cs_label(lf_figures, 12, 0, 'Markersize', sticky=W)
    dropd_markersize = cs_dropd(lf_figures, 13, 0, markersizes, sticky=W)
    dropd_markersize.set(vallist[6])
    cs_label(lf_figures, 14, 0, 'Linewidth', sticky=W)
    dropd_linewidth = cs_dropd(lf_figures, 15, 0, markersizes, sticky=W)
    dropd_linewidth.set(vallist[7])
    cs_label(lf_figures, 16, 0, 'Scientific notation for ax labels, so:\n10^-n < data < 10^m', sticky=W)
    cs_label(lf_figures, 17, 0, 'n', sticky=W)
    dropd_laxpowerlimits = cs_dropd(lf_figures, 18, 0, range(-9, 1), sticky=W)
    dropd_laxpowerlimits.set(vallist[8][0])
    cs_label(lf_figures, 19, 0, 'm', sticky=W)
    dropd_uaxpowerlimits = cs_dropd(lf_figures, 20, 0, range(1, 9), sticky=W)
    dropd_uaxpowerlimits.set(vallist[8][1])

    lf_drawlattice = LabelFrame(uf, text="Lattice painter", padx=5, pady=5)
    lf_drawlattice.grid(row=1, column=1, sticky=W+E+N+S, padx=10, pady=10)
    showlat = cs_checkbox(lf_drawlattice, 0, 0, 'Show Lattice', vallist[9], sticky=W)
    showqk = cs_checkbox(lf_drawlattice, 1, 0, 'Show quad strengths', vallist[10], sticky=W)
    showqn = cs_checkbox(lf_drawlattice, 2, 0, 'Show quad numbers', vallist[10], sticky=W)
    showfom = cs_checkbox(lf_drawlattice, 3, 0, 'Show diagnostic elements', vallist[11], sticky=W)

    cp_button(lf, 'Save and Close', _save, side=RIGHT, fill=BOTH, expand=True)
    cp_button(lf, 'Close', _cancel, side=RIGHT, fill=BOTH, expand=True)
    return
Exemplo n.º 27
0
class App(Frame):
    results_window = False

    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.__init_main(*args, **kwargs)

    def __init_main(self, *args, **kwargs):
        self.root = args[0]
        self.root.filename = ""
        self.root.wm_title("RSTool")
        self.root.protocol("WM_DELETE_WINDOW", self.__delete_root_window)
        self.root.bind("<Destroy>", self.__destroy_root_window)

        self.menubar = Menu(self.root)
        self.filemenu = Menu(self.menubar)
        self.filemenu.add_command(label="Save as...",
                                  command=self.save_to_file)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self.root.destroy)
        self.menubar.add_cascade(label="File", menu=self.filemenu)

        self.root.config(menu=self.menubar)

        self.tests = [
            Frequency,
            BlockFrequency,
            Runs,
            LongestRunOfOnes,
            Rank,
            DiscreteFourierTransform,
            Universal,
            Serial,
            ApproximateEntropy,
            CumulativeSums,
            RandomExcursions,
            RandomExcursionsVariant,
        ]
        self.slowtests = [
            NonOverlappingTemplateMatching,  # Slow
            OverlappingTemplateMatching,  # Slow
            LinearComplexity  # Slow
        ]
        # self.run_RandomWalkPlot = IntVar(self.root)

        rcounter = 0

        # Create and pack the title row:
        title = "NYUAD\nCenter for Cyber Security\nRandomness Testing Tool\nv0.9.0"
        self.l1 = Label(self.root, text=title)
        self.l1.grid(column=0, row=rcounter, columnspan=2, sticky=N)
        # self.l1.pack()
        rcounter += 1

        # Create and pack the "Open File" button and bind the loadFile method:
        self.b1 = Button(self.root, text="Open File", command=self.loadFile)
        self.b1.grid(column=0, row=rcounter, columnspan=1, pady=5)
        # rcounter += 1
        # self.b1.pack()

        # Create and pack the filename:
        self.l2 = Label(self.root, text=self.root.filename)
        self.l2.grid(column=1,
                     row=rcounter,
                     columnspan=2,
                     sticky=W,
                     padx=(5, 10))
        # self.l1.pack()
        rcounter += 1

        # Create textbox for bit-limit
        self.nl = Label(self.root,
                        text="Number of bits to test: (0 to test all)")
        self.nl.grid(column=0, row=rcounter, columnspan=1)
        rcounter += 1
        self.nt = Text(self.root, state="normal", width="15", height="1")
        self.nt.insert(END, "0")
        self.nt.grid(column=0,
                     row=rcounter,
                     columnspan=1,
                     padx=10,
                     pady=(0, 5))
        rcounter += 1

        # Create and pack the "Select/Deselect All" button and bind the checkAll method:
        self.b2 = Button(self.root,
                         text="Select/Deselect All Tests",
                         command=self.checkAll)
        self.b2.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5))
        rcounter += 1
        # self.b2.pack()

        # Create and pack the "Select/Deselect Fast" button and bind the checkFast method:
        self.b3 = Button(self.root,
                         text="Select/Deselect Fast Tests",
                         command=self.checkFast)
        self.b3.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5))
        rcounter += 1
        # self.b2.pack()

        # Create and pack the "Select/Deselect Slow" button and bind the checkSlow method:
        self.b4 = Button(self.root,
                         text="Select/Deselect Slow Tests",
                         command=self.checkSlow)
        self.b4.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5))
        rcounter += 1
        # self.b2.pack()

        # Set IntVars for each test to check if it is selected to run:
        for test in self.tests + self.slowtests:
            setvar = "self.run_%s = IntVar(self.root)" % (test.__name__)
            exec(setvar)
            setvar = ""
            for i in range(func_data[test.__name__][1]):
                setvar = "self.%s_arg_%s = IntVar(self.root)" % (
                    test.__name__, func_data[test.__name__][2][i])

            # Example:
            # self.run_Frequency = IntVar(self.root)

        # Create and pack the checkbutton for each test and bind its IntVar to it:
        for test in self.tests + self.slowtests:
            make = [
                "self.cb_%s = " % (test.__name__), "Checkbutton(self.root, ",
                "text='%s ', " % (func_data[test.__name__][0]),
                "variable=self.run_%s)" % (test.__name__)
            ]
            make = "".join(make)
            grid = [
                "self.cb_%s.grid(" % (test.__name__),
                "column=0, row=%d, sticky=W)" % rcounter
            ]
            grid = "".join(grid)
            # args stuff
            rcounter += 1
            # pack = "self.cb_%s.pack()" % (test.__name__)
            exec(make)
            exec(grid)
            # exec(pack)
            # Example:
            # self.cb1 = Checkbutton(self.root, text="Frequency",
            # variable=self.run_Frequency)
            # self.cb1.pack()

        # Create and pack the "Run Tests" button and bind the runTests method:
        self.rb = Button(self.root, text="Run Tests", command=self.runTests)
        self.rb.grid(column=0, row=rcounter, columnspan=2)
        rcounter += 1
        # self.rb.pack()

        self.root.resizable(0, 0)
        self.root.lift()
        self.root.attributes('-topmost', True)
        self.root.after_idle(self.root.attributes, '-topmost', False)

    def __delete_root_window(self):
        # print "delete_root_window"
        try:
            self.root.destroy()
        except:
            pass

    def __destroy_root_window(self, event):
        # print "destroy_root_window", event
        pass

    def __delete_results_window(self):
        # print "delete_results_window"
        try:
            self.results_window.destroy()
        except:
            pass

    def __destroy_results_window(self, event):
        # print "destroy_results_window", event
        self.results_window = False

    def __make_results_window(self):
        # wname = "results_window"
        self.results_window = Toplevel(self, name="results_window")
        self.results_window.protocol("WM_DELETE_WINDOW",
                                     self.__delete_results_window)
        self.results_window.bind("<Destroy>", self.__destroy_results_window)
        self.results_window.wm_title("Test Results")
        self.results_window.config(menu=self.menubar)

        self.results_save_button = Button(self.results_window,
                                          text="Save to File",
                                          command=self.save_to_file)
        self.results_save_button.pack()

        self.results_text = Text(self.results_window,
                                 state="normal",
                                 width="70",
                                 height="50")
        self.results_text.pack(fill="both", expand=True, padx=10)

    def loadFile(self):
        # print "loadFile called!"
        self.root.filename = tkFileDialog.askopenfilename(
            initialdir=".", title="Select file...")
        # print (self.root.filename)
        # self.l2.config(text=self.root.filename)

    def save_to_file(self):
        if self.results_window:
            self.root.outfile = tkFileDialog.asksaveasfile(
                mode='w',
                defaultextension=".txt",
                initialdir=".",
                initialfile="output",
                title="Save as...")
            data = str(self.results_text.get(0.0, END))
            self.root.outfile.write(data)
            self.root.outfile.close()

    def checkAll(self):
        all_checked = 1
        for test in self.tests + self.slowtests:
            if not eval('self.run_' + test.__name__ + '.get()'):
                all_checked = 0
        val = 1 - all_checked
        for test in self.tests + self.slowtests:
            eval('self.run_' + test.__name__).set(val)

    def checkFast(self):
        all_checked = 1
        for test in self.tests:
            if not eval('self.run_' + test.__name__ + '.get()'):
                all_checked = 0
        val = 1 - all_checked
        for test in self.tests:
            eval('self.run_' + test.__name__).set(val)

    def checkSlow(self):
        all_checked = 1
        for test in self.slowtests:
            if not eval('self.run_' + test.__name__ + '.get()'):
                all_checked = 0
        val = 1 - all_checked
        for test in self.slowtests:
            eval('self.run_' + test.__name__).set(val)

    def text_insert(self, text, noret=False):
        if not self.results_window:
            self.__make_results_window()
        place = 'end'
        if not self.results_text:
            raise Exception("results_text does not exist")
        if type(text) != str:
            raise TypeError("Expected str, got %s: %s" % (type(text), text))
        # self.results_text.configure(state="normal")  # enables changing content
        self.results_text.insert(place, text + ["\n", ""][noret])
        self.update_idletasks()
        # self.results_text.configure(state="disabled") # relocks the content

    def getn(self):
        return int(self.nt.get("1.0", END))

    def setn(self, n):
        self.nt.delete(1.0, END)
        self.nt.insert(END, str(int(n)))

    def runTests(self):
        if self.results_window:
            self.__delete_results_window()
        cont = True
        try:
            n = self.getn()
            if n < 0:
                raise ValueError
        except Exception as e:
            print 'Error:', e
            self.setn("0")
            cont = False
        if cont:
            try:
                if self.root.filename == "":
                    raise ValueError("No file selected")
                e = read_data(self.root.filename)
                if n == 0:
                    n = len(e)
                e = e[:n]
                if len(e) == 0:
                    raise LengthError("No data in file")
                out = "Data read:\n"
                out += "e = "
                out += "".join([str(i) for i in e][:min(32, len(e))])
                out += ["", "..."][len(e) > 32] + "\n"
                out += "See test_results folder for detailed results\n"
                self.text_insert(out)
            except:
                self.text_insert("Failed to read data.")
                cont = False
        if cont:
            # for test in self.tests:
            #   self.text_insert("self.run_" + test.__name__ + " = " + str(eval(
            #                    "self.run_" + test.__name__ + ".get()")))
            test_dir = "./test_results"
            if not os.path.exists(test_dir):
                os.makedirs(test_dir)
            for test in self.tests + self.slowtests:
                try:
                    if eval("self.run_" + test.__name__ + ".get()"):
                        self.text_insert("Running " + test.__name__ + ":")
                        output = test(e)
                        self.text_insert(["Non-Random", "Random"][output])
                        self.text_insert("\n")
                except Exception as e:
                    self.text_insert("\nError in %s: %s\n" %
                                     (test.__name__, e.__str__()))

            self.text_insert("Tests completed.")
Exemplo n.º 28
0
    def parameter_window(self):
        """
        Setting other parameters using an emerging window
        CNN parameters, CUDA device, post-processing....

        """
        t = Toplevel(self.master)
        t.wm_title("Other parameters")

        # data parameters
        t_data = LabelFrame(t, text="data options:")
        t_data.grid(row=0, sticky="WE")
        checkPretrain = Checkbutton(t_data,
                                    text="Register modalities",
                                    var=self.param_register_modalities)
        checkPretrain.grid(row=0, sticky='W')
        checkSkull = Checkbutton(t_data,
                                 text="Skull-strip modalities",
                                 var=self.param_skull_stripping)
        checkSkull.grid(row=1, sticky="W")
        checkDenoise = Checkbutton(t_data,
                                   text="Denoise masks",
                                   var=self.param_denoise)
        checkDenoise.grid(row=2, sticky="W")

        denoise_iter_label = Label(t_data,
                                   text=" Denoise iter:               ")
        denoise_iter_label.grid(row=3, sticky="W")
        denoise_iter_entry = Entry(t_data,
                                   textvariable=self.param_denoise_iter)
        denoise_iter_entry.grid(row=3, column=1, sticky="E")

        check_tmp = Checkbutton(t_data,
                                text="Save tmp files",
                                var=self.param_save_tmp)
        check_tmp.grid(row=4, sticky="W")
        checkdebug = Checkbutton(t_data,
                                 text="Debug mode",
                                 var=self.param_debug)
        checkdebug.grid(row=5, sticky="W")

        # model parameters
        t_model = LabelFrame(t, text="Model:")
        t_model.grid(row=5, sticky="EW")

        maxepochs_label = Label(t_model, text="Max epochs:                  ")
        maxepochs_label.grid(row=6, sticky="W")
        maxepochs_entry = Entry(t_model, textvariable=self.param_max_epochs)
        maxepochs_entry.grid(row=6, column=1, sticky="E")

        trainsplit_label = Label(t_model, text="Validation %:           ")
        trainsplit_label.grid(row=7, sticky="W")
        trainsplit_entry = Entry(t_model, textvariable=self.param_train_split)
        trainsplit_entry.grid(row=7, column=1, sticky="E")

        batchsize_label = Label(t_model, text="Test batch size:")
        batchsize_label.grid(row=8, sticky="W")
        batchsize_entry = Entry(t_model, textvariable=self.param_batch_size)
        batchsize_entry.grid(row=8, column=1, sticky="E")

        mode_label = Label(t_model, text="Verbosity:")
        mode_label.grid(row=9, sticky="W")
        mode_entry = Entry(t_model, textvariable=self.param_net_verbose)
        mode_entry.grid(row=9, column=1, sticky="E")

        #gpu_mode = Checkbutton(t_model,
        #                         text="GPU:",
        #                         var=self.param_mode)
        #gpu_mode.grid(row=10, sticky="W")

        gpu_number = Label(t_model, text="GPU number:")
        gpu_number.grid(row=10, sticky="W")
        gpu_entry = Entry(t_model, textvariable=self.param_gpu_number)
        gpu_entry.grid(row=10, column=1, sticky="W")

        # training parameters
        tr_model = LabelFrame(t, text="Training:")
        tr_model.grid(row=12, sticky="EW")

        balanced_label = Label(tr_model, text="Balanced dataset:    ")
        balanced_label.grid(row=13, sticky="W")
        balanced_entry = Entry(tr_model,
                               textvariable=self.param_balanced_dataset)
        balanced_entry.grid(row=13, column=1, sticky="E")

        fraction_label = Label(tr_model, text="Fraction negative/positives: ")
        fraction_label.grid(row=14, sticky="W")
        fraction_entry = Entry(tr_model,
                               textvariable=self.param_fract_negatives)
        fraction_entry.grid(row=14, column=1, sticky="E")

        # postprocessing parameters
        t_post = LabelFrame(t, text="Post-processing:  ")
        t_post.grid(row=15, sticky="EW")
        t_bin_label = Label(t_post, text="Out probability th:      ")
        t_bin_label.grid(row=16, sticky="W")
        t_bin_entry = Entry(t_post, textvariable=self.param_t_bin)
        t_bin_entry.grid(row=16, column=1, sticky="E")

        l_min_label = Label(t_post, text="Min out region size:         ")
        l_min_label.grid(row=17, sticky="W")
        l_min_entry = Entry(t_post, textvariable=self.param_l_min)
        l_min_entry.grid(row=17, column=1, sticky="E")

        vol_min_label = Label(t_post, text="Min vol error (ml):   ")
        vol_min_label.grid(row=18, sticky="W")
        vol_min_entry = Entry(t_post, textvariable=self.param_min_error)
        vol_min_entry.grid(row=18, column=1, sticky="E")
Exemplo n.º 29
0
class ContinuousTMPViewer(object):
    def __init__(self,
                 env_region,
                 regions=[],
                 tl_x=0,
                 tl_y=0,
                 width=500,
                 height=250,
                 title='Grid',
                 background='tan'):
        self.tk = Tk()

        self.tk.withdraw()
        self.top = Toplevel(self.tk)
        self.top.wm_title(title)
        self.top.protocol('WM_DELETE_WINDOW', self.top.destroy)

        self.env_region = env_region
        self.regions = regions
        self.tl_x = tl_x
        self.tl_y = tl_y
        self.width = width
        self.height = height
        self.canvas = Canvas(self.top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()

        self.move_frame(self.tl_x, self.tl_y)

        self.dist_to_pixel = (self.width -
                              2 * PIXEL_BUFFER) / (self.env_region.w)
        self.dist_width = self.width / self.dist_to_pixel
        self.dist_height = self.height / self.dist_to_pixel
        self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT
        self.robot_dist = self.dist_height / 2.

        self.robot = []
        self.blocks = []
        self.holding = None
        self.draw_environment()

    def center(self):
        self.top.update_idletasks()
        w = self.top.winfo_screenwidth()
        h = self.top.winfo_screenheight()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        x = w / 2 - size[0] / 2
        y = h / 2 - size[1] / 2
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def move_frame(self, x, y):
        self.top.update_idletasks()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def t_x(self, x):
        return self.dist_to_pixel * (x + self.dist_width / 2.)

    def t_y(self, y):
        return self.ground_height - self.dist_to_pixel * y

    def draw_block(self, block, x):
        self.blocks.append(
            self.canvas.create_rectangle(self.t_x(x - block.w / 2.),
                                         self.t_y(0),
                                         self.t_x(x + block.w / 2.),
                                         self.t_y(block.h),
                                         fill=block.color,
                                         outline='black',
                                         width=2))

    def draw_holding(self, block, x):
        self.holding = self.canvas.create_rectangle(
            self.t_x(x - block.w / 2.),
            self.t_y(self.robot_dist - SUCTION_HEIGHT / 2 - block.h),
            self.t_x(x + block.w / 2.),
            self.t_y(self.robot_dist - SUCTION_HEIGHT / 2),
            fill=block.color,
            outline='black',
            width=2)

    def draw_region(self, region):
        self.environment.append(
            self.canvas.create_rectangle(self.t_x(region.x - region.w / 2.),
                                         self.ground_height,
                                         self.t_x(region.x + region.w / 2.),
                                         self.height,
                                         fill='red',
                                         outline='black',
                                         width=2))

    def draw_environment(self, table_color='lightgrey', bin_color='grey'):
        self.environment = [
            self.canvas.create_rectangle(self.t_x(-self.env_region.w / 2),
                                         self.ground_height,
                                         self.t_x(self.env_region.w / 2),
                                         self.height,
                                         fill=table_color,
                                         outline='black',
                                         width=2)
        ]
        for region in self.regions:
            self.draw_region(region)

    def draw_robot(self, x, color='yellow'):
        self.robot = [
            self.canvas.create_rectangle(
                self.t_x(x - SUCTION_WIDTH / 2.),
                self.t_y(self.robot_dist - SUCTION_HEIGHT / 2.),
                self.t_x(x + SUCTION_WIDTH / 2.),
                self.t_y(self.robot_dist + SUCTION_HEIGHT / 2.),
                fill=color,
                outline='black',
                width=2),
            self.canvas.create_rectangle(
                self.t_x(x - STEM_WIDTH / 2.),
                self.t_y(self.robot_dist + SUCTION_HEIGHT / 2.),
                self.t_x(x + STEM_WIDTH / 2.),
                self.t_y(self.robot_dist + SUCTION_HEIGHT / 2. + STEM_HEIGHT),
                fill=color,
                outline='black',
                width=2),
        ]

    def clear_state(self):
        for block in self.blocks:
            self.canvas.delete(block)
        for part in self.robot:
            self.canvas.delete(part)
        if self.holding is not None:
            self.canvas.delete(self.holding)

    def clear_all(self):
        self.canvas.delete('all')

    def save(self, filename):

        from PIL import ImageGrab
        ImageGrab.grab((0, 0, self.width, self.height)).save(filename + '.jpg')
Exemplo n.º 30
0
class Board:
    def __init__(self, width, height, title = "Boids"):
        """ A board for boids to explore """
        from Tkinter import Tk, Canvas, Toplevel
        self.colors = ["white", "black", "red", "yellow", "blue", "green", "purple", "pink", "cyan", "turquoise", "gray"]
        self.width = width
        self.height = height
        self.distance = 10
        self.boids = []
        self.oldVector = []
        self.title = title
        self.app = Tk()
        self.app.withdraw()
        self.win = Toplevel()
        self.win.wm_title(title)
        self.canvas = Canvas(self.win,
                             width=self.width,
                             height=self.height)
        self.canvas.pack(side = 'bottom', expand = "yes", anchor = "n",
                         fill = 'both')
        self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW',self.close)
        #self.canvas.bind("<Configure>", self.changeSize)
        self.draw()

    def close(self):
        """ close the window """
        self.app.destroy()

    def draw(self):
        """ Initialize the board. You must do this if you ever want to see the path """
        print "Drawing...",
        self.canvas.delete("boid")
        for boid in self.boids:
            self.drawBoid( boid )
        self.canvas.update()
        print "Done!"

    def drawBoid(self, boid):
        size = 40
        angle = 80
        x = boid.x - size/2
        y = boid.y - size/2
        start = ((boid.dir + 180 + angle/2) - 55) % 360
        color = self.colors[boid.color]
        self.canvas.create_arc(x, y, x + size, y + size,
                               start = start, extent = angle/2,
                               fill = color, outline = color, tag = "boid")
        
    def addBoid(self, boid):
        self.boids.append( boid )
        self.oldVector.append( 0 )
        self.draw()

    def dist(self, x1, y1, x2, y2):
        return math.sqrt( (x1 - x2) ** 2 + (y1 - y2) ** 2)

    def angleTo(self, b1, b2):
        # figure out angle from boid1 to boid2
        # this is just a test!
        if self.boids[b1].x < self.boids[b2].x:
            return -10
        # return - if to the right, + if to the left
        else:
            return 10

    def avoid(self, num, radius):
        for i in range(len(self.boids)):
            if i != num:
                if self.dist(self.boids[i].x, self.boids[i].y,
                             self.boids[num].x, self.boids[num].y ) < radius:
                    return -self.angleTo( num, i)
        return 0.0
    
    def copy(self, num, radius):
        # if within radius, get closer to their angle
        # return - if to the right, + if to the left
        return 0

    def center(self, num, radius):
        # make yoru angle head toward center
        # return - if to the right, + if to the left
        return 0

    def view(self, num, radius):
        # try to have a clear view
        # return - if to the right, + if to the left
        return 0

    def adjustDirections(self, weights):
        radius = 40
        for boidNum in range(len(self.boids)):
            avoidVector = self.avoid( boidNum, radius )
            copyVector = self.copy( boidNum, radius )
            centerVector = self.center( boidNum, radius )
            viewVector = self.view( boidNum, radius )
            newVector = int(weights[0] * avoidVector + weights[1] * copyVector + weights[2] * centerVector + weights[3] * viewVector)
            self.boids[boidNum].dir += newVector
            self.oldVector[boidNum] = newVector

    def move(self):
        """ Make the boids move """
        self.adjustDirections([1., 1., 1., 1.]) # pass in weights: avoid, copy, center, view
        for boid in self.boids:
            boid.x += self.distance * math.cos( boid.dir / 180.0 * math.pi)
            boid.y -= self.distance * math.sin( boid.dir / 180.0 * math.pi)
            if boid.x > self.width:
                boid.x = 0
            if boid.x < 0:
                boid.x = self.width - 1
            if boid.y > self.height:
                boid.y = 0
            if boid.y < 0:
                boid.y = self.height - 1
        self.draw()
class DrawingWindow:
    def __init__(self,
                 width,
                 height,
                 x_min,
                 x_max,
                 y_min,
                 y_max,
                 title,
                 parent=None):
        self.title = title
        if parent:
            self.parent = parent
            self.top = parent.getWindow(title)
        else:
            self.tk = Tk()
            self.tk.withdraw()
            self.top = Toplevel(self.tk)
            self.top.wm_title(title)
            self.top.protocol('WM_DELETE_WINDOW', self.top.destroy)
        self.window_width = width
        self.window_height = height
        self.canvas = Canvas(self.top,
                             width=self.window_width,
                             height=self.window_height,
                             background="white")
        self.canvas.pack()

        self.x_scale = width / float(
            x_max - x_min)  # multiply an input value by this to get pixels
        self.y_scale = height / float(y_max - y_min)

        self.x_min = x_min
        self.y_min = y_min
        self.x_max = x_max
        self.y_max = y_max

    def scale_x(self, x):
        return self.x_scale * (x - self.x_min)

    def scale_y(self, y):
        return self.window_height - self.y_scale * (y - self.y_min)

    def draw_point(self, x, y, color="blue", radius=1):
        window_x = self.scale_x(x)
        window_y = self.scale_y(y)
        return self.canvas.create_rectangle(window_x - radius,
                                            window_y - radius,
                                            window_x + radius,
                                            window_y + radius,
                                            fill=color,
                                            outline=color)

    def draw_text(self, x, y, label):
        return self.canvas.create_text(self.scale_x(x),
                                       self.scale_y(y),
                                       text=label)
        # font="Arial 20",fill="#ff0000"

    def draw_poly(self, verts, color="black", outline="black"):
        return self.canvas.create_polygon(
            [(self.scale_x(point.x), self.scale_y(point.y))
             for point in verts],
            fill=color,
            outline=outline)

    def draw_rect(self, (x1, y1), (x2, y2), color="black"):
Exemplo n.º 32
0
class AboutPopUp():
    '''
    there is a lot of work to do here also,
    but is a quite good and functional starting point...
    
    first put as child of Toplevel
    then change to grid
    '''
    def __init__(self, **kwargs):
        ''' (under development)'''

        master = None
        title = 'AboutPopUp'
        licence = None

        if 'master' in kwargs.keys():
            master = kwargs['master']
        if 'title' in kwargs.keys():
            title = kwargs['title']
        if 'licence' in kwargs.keys():
            licence = kwargs['licence']

        self.im_smlogo = PhotoImage(file="./lib/gui/img/small_logo2.ppm")
        self.im_logo2 = PhotoImage(file="./lib/gui/img/logo2.ppm")
        self.master = master
        self._title_ = title
        self._licence_ = licence

        self.set_self_vertex()
        self.create_content()

    def set_self_vertex(self):

        ws, hs, w_main, h_main, x_main, y_main = self.master.MAINVERTEX
        # calculate the greatness
        w_pop = w_main
        h_pop = h_main * 14 / 21

        x_pop = x_main + w_main + 30
        y_pop = y_main + h_main - h_pop - 140
        #print w_pop, h_pop, x_pop, y_pop
        self._vertex_ = [w_pop, h_pop, x_pop, y_pop]

    def create_content(self):

        self.pop = Toplevel(self.master, bg="white")
        self.pop.grab_set()  # when you show the popup

        self.pop.wm_title(' ' * 5 + self._title_)
        self.pop.geometry('{:d}x{:d}+{:d}+{:d}'.format(*self._vertex_))

        leftcolumn = Frame(self.pop, bg="white")
        Label(leftcolumn, bg="white").pack(side="top", fill="both", pady=30)
        Label(leftcolumn,
              bg="white", image=self.im_logo2).pack(side="top",
                                                    fill="both",
                                                    padx=10)  #side= LEFT,
        leftcolumn.pack(side="left", fill='both', padx=1)

        rightcolumn = Frame(self.pop, bg="white")
        firstrow = Frame(rightcolumn, bg="white")
        Frame(rightcolumn, bg="white").pack(side="top", pady=10, padx=0)

        Label(firstrow,
              text="GROTOLAM",
              fg="Gray13",
              bg="white",
              font="Verdana 13 bold").pack(side="left", pady=20)
        Label(firstrow, text='', bg="white").pack(side="left", padx=40)
        firstrow.pack(side="top", padx=0)

        secrow = Frame(rightcolumn, bg="white")
        Label(secrow,
              text="v " + __version__.split()[2],
              fg="Gray13",
              bg="white",
              font="Verdana 10").pack(side="left")
        Label(secrow, text='', bg="white").pack(side="left", padx=75)
        secrow.pack(side="top", padx=0)

        # lets create space to do some stuff ...
        Frame(rightcolumn, bg="white").pack(side="top", pady=20, padx=0)

        thirdrow = Frame(rightcolumn, bg="white")

        Label(thirdrow,
              text="2018 Python version by",
              fg="Gray13",
              bg="white",
              font="Verdana 10").pack(side="left")
        Label(thirdrow, text='', bg="white").pack(side="left", padx=16)
        thirdrow.pack(side="top", padx=0)

        fourthrow = Frame(rightcolumn, bg="white")
        Label(fourthrow,
              text="Hernan Chavez Thielemann",
              fg="Gray13",
              bg="white",
              font="Verdana 10").pack(side="left")
        Label(fourthrow, text='', bg="white").pack(side="left", padx=1)
        fourthrow.pack(side="top", padx=0)

        fifthrow = Frame(rightcolumn, bg="white")
        Label(fifthrow, bg="white", image=self.im_smlogo).pack(side="left",
                                                               fill="both",
                                                               padx=10)
        fifthrow.pack(side="top", padx=0)

        sixthrow = Frame(rightcolumn, bg="white")
        href = Label(sixthrow,
                     bg="white",
                     font="Verdana 10",
                     text="Small web page",
                     fg="blue",
                     cursor="hand2")
        f = Font(href, href.cget("font"))
        f.configure(underline=True)
        href.configure(font=f)
        href.pack(side="left")
        href.bind("<Button-1>", self.callback)

        Label(sixthrow, text='', bg="white").pack(side="left", padx=40)
        sixthrow.pack(side="top", padx=0)

        lastrow = Frame(rightcolumn, bg="white")
        self.bottom_button_row(lastrow)
        rightcolumn.pack(side="right", fill='both', padx=5)

    def callback(self, event):
        open_new(r"http://www.polito.it/small")

    def bottom_button_row(self, _row_):

        b2 = Button(_row_, text='Close', bg="white", command=self.exit_pop)
        b2.pack(side="right", padx=10, pady=4)
        b1 = Button(_row_, text='Licence', bg="white", command=self._licence_)
        b1.pack(side="right", padx=10, pady=20)
        _row_.pack(side="bottom")

    def openlicence(self):

        print 'opening licence file'

    def exit_pop(self):
        self.pop.grab_release()  # to return to normal
        self.pop.destroy()
Exemplo n.º 33
0
class PromptPopUp_old():
    '''the future description:
            "Neat & tidy prompt pop up to request input"
        
        there is a lot of work to do here :
        make it class
        clean functions to make it generic
        add extra parameters such as:
                    buttons
                    title
                    dimensions*
                    
       >but is a functional starting point<
    '''
    def __init__(self, **kwargs):
        ''' (under development)'''

        master = None
        briefing = ''
        entries_txt = []
        entries_val = []
        title = 'PromptPopUp'

        if 'master' in kwargs.keys():
            master = kwargs['master']
        if 'briefing' in kwargs.keys():
            briefing = kwargs['briefing']
        if 'entries_txt' in kwargs.keys():
            entries_txt = kwargs['entries_txt']
        if 'entries_val' in kwargs.keys():
            entries_val = kwargs['entries_val']
        if 'title' in kwargs.keys():
            title = kwargs['title']

        self.master = master
        self._briefing_ = briefing
        self._entries_ = entries_txt
        self._defvals_ = entries_val
        self._title_ = title

        self.ent_c = []

        self.set_self_vertex()
        self.create_content()

    def set_self_vertex(self):
        from main_gui import MAINVERTEX
        ws, hs, w_main, h_main, x_main, y_main = MAINVERTEX
        # calculate the greatness
        self.entr_maxlen = int(len(max(self._entries_, key=len)) * 2.25 / 3.0)
        w_pop = w_main - 40
        h_pop = h_main * 12 / 21

        x_pop = x_main + w_main - 30
        y_pop = y_main + h_main - h_pop
        #print w_pop, h_pop, x_pop, y_pop
        self._vertex_ = [w_pop, h_pop, x_pop, y_pop]

    def create_content(self):

        self.pop = Toplevel(self.master)
        self.pop.grab_set()  # when you show the popup

        self.pop.wm_title(' ' * 20 + self._title_)
        self.pop.geometry('{:d}x{:d}+{:d}+{:d}'.format(*self._vertex_))

        label0 = Label(self.pop, text=self._briefing_)
        label0.pack(side="top", fill="both", expand=True, padx=100, pady=20)
        #    just a line
        bottom_hline_deco(self.pop)
        # lets create space to do some stuff ...

        row2fill = Frame(self.pop)

        for e in range(len(self._entries_)):
            self.ent_c.append(
                create_entry(row2fill, self._entries_[e], self._defvals_[e],
                             self.entr_maxlen))
        row2fill.pack(side="top", padx=1, pady=5)

        self.bottom_button_row()

        self.master.solv_b.config(bg='gray40', width=45)  #cyan')
        #self.master.solv_b.flash()
        #self.pop.mainloop()

    def bottom_button_row(self):

        _br_ = Frame(self.pop)
        b1 = Button(_br_, text='Save', command=(lambda: self.save_it()))
        b1.pack(side="right", padx=10, pady=20)
        b2 = Button(_br_, text='Quit', command=(lambda: self.exit_pop()))
        b2.pack(side="right", padx=10, pady=4)
        _br_.pack(side="bottom", expand=True)

    def save_it(self):

        self.master._solvatedinfo_ = get_entriesvalue(self.ent_c)
        self.exit_pop()

    def exit_pop(self):

        self.pop.grab_release()  # to return to normal
        self.master.solv_b.config(bg='lightgrey', width=29)
        self.pop.destroy()
Exemplo n.º 34
0
class Evolution(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        
        self.parent = parent

        self.initUI()
        

    def configure(self):
        self.conf = Toplevel(self)
        self.conf.wm_title("Configure Universe")

        self.wc.reconfigure(self)
    

    def initUI(self):
        #create initial Beings object (not instantiated until live is called)
        self.wc = WorldConfiguration()

        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(2, weight=1)
        self.columnconfigure(4, pad=7)
        self.rowconfigure(3, weight=1)

        lbl = Label(self, text="PyLife")
        lbl.grid(sticky = W, padx=25, pady=5)

        self.world = Canvas(self, background="#7474DB")
        self.world.grid(row=1, column=0, columnspan=3, rowspan=8, padx=5, sticky=E+W+N+S)
        
        self.sbtn = Button(self, text="Stop")
        self.sbtn.grid(row=1, column=4, pady = 5, sticky=E)

        self.bbox = Text(self, height=20, width=36)
        self.bbox.grid(row=3, column = 4, padx=5, sticky=E+W+N+S)

        self.bbox1 = Text(self, height=11, width=36)
        self.bbox1.grid(row=4, column=4, padx=5, sticky=E+W+N+S)

        self.cbtn = Button(self, text="Close", command=self.parent.destroy)
        self.cbtn.grid(row=9, column=4, pady=5)

        self.cnfbtn = Button(self, text="Configure Universe")
        self.cnfbtn.grid(row=9, column=0, padx=5)

        self.timelbl = Text(self, height=1, width=10)
        self.timelbl.grid(row=2, column=4, pady=5 )
       

        b = Beings(self)
        abtn = Button(self, text="Start", command=b.live)  #Beings(cnfbtn, world, 4, 10, sbtn, bbox, bbox1, timelbl).live)
        abtn.grid(row=1, column=4, pady=5, sticky=W)

        self.cnfbtn.config(command=b.configure)

    def close(self):
        self.parent.destroy
Exemplo n.º 35
0
class Board:
    def __init__(self, width, height, title="Boids"):
        """ A board for boids to explore """
        from Tkinter import Tk, Canvas, Toplevel
        self.colors = [
            "white", "black", "red", "yellow", "blue", "green", "purple",
            "pink", "cyan", "turquoise", "gray"
        ]
        self.width = width
        self.height = height
        self.distance = 10
        self.boids = []
        self.oldVector = []
        self.title = title
        self.app = Tk()
        self.app.withdraw()
        self.win = Toplevel()
        self.win.wm_title(title)
        self.canvas = Canvas(self.win, width=self.width, height=self.height)
        self.canvas.pack(side='bottom', expand="yes", anchor="n", fill='both')
        self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW', self.close)
        #self.canvas.bind("<Configure>", self.changeSize)
        self.draw()

    def close(self):
        """ close the window """
        self.app.destroy()

    def draw(self):
        """ Initialize the board. You must do this if you ever want to see the path """
        print "Drawing...",
        self.canvas.delete("boid")
        for boid in self.boids:
            self.drawBoid(boid)
        self.canvas.update()
        print "Done!"

    def drawBoid(self, boid):
        size = 40
        angle = 80
        x = boid.x - size / 2
        y = boid.y - size / 2
        start = ((boid.dir + 180 + angle / 2) - 55) % 360
        color = self.colors[boid.color]
        self.canvas.create_arc(x,
                               y,
                               x + size,
                               y + size,
                               start=start,
                               extent=angle / 2,
                               fill=color,
                               outline=color,
                               tag="boid")

    def addBoid(self, boid):
        self.boids.append(boid)
        self.oldVector.append(0)
        self.draw()

    def dist(self, x1, y1, x2, y2):
        return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)

    def angleTo(self, b1, b2):
        # figure out angle from boid1 to boid2
        # this is just a test!
        if self.boids[b1].x < self.boids[b2].x:
            return -10
        # return - if to the right, + if to the left
        else:
            return 10

    def avoid(self, num, radius):
        for i in range(len(self.boids)):
            if i != num:
                if self.dist(self.boids[i].x, self.boids[i].y,
                             self.boids[num].x, self.boids[num].y) < radius:
                    return -self.angleTo(num, i)
        return 0.0

    def copy(self, num, radius):
        # if within radius, get closer to their angle
        # return - if to the right, + if to the left
        return 0

    def center(self, num, radius):
        # make yoru angle head toward center
        # return - if to the right, + if to the left
        return 0

    def view(self, num, radius):
        # try to have a clear view
        # return - if to the right, + if to the left
        return 0

    def adjustDirections(self, weights):
        radius = 40
        for boidNum in range(len(self.boids)):
            avoidVector = self.avoid(boidNum, radius)
            copyVector = self.copy(boidNum, radius)
            centerVector = self.center(boidNum, radius)
            viewVector = self.view(boidNum, radius)
            newVector = int(weights[0] * avoidVector +
                            weights[1] * copyVector +
                            weights[2] * centerVector +
                            weights[3] * viewVector)
            self.boids[boidNum].dir += newVector
            self.oldVector[boidNum] = newVector

    def move(self):
        """ Make the boids move """
        self.adjustDirections([1., 1., 1., 1.
                               ])  # pass in weights: avoid, copy, center, view
        for boid in self.boids:
            boid.x += self.distance * math.cos(boid.dir / 180.0 * math.pi)
            boid.y -= self.distance * math.sin(boid.dir / 180.0 * math.pi)
            if boid.x > self.width:
                boid.x = 0
            if boid.x < 0:
                boid.x = self.width - 1
            if boid.y > self.height:
                boid.y = 0
            if boid.y < 0:
                boid.y = self.height - 1
        self.draw()
Exemplo n.º 36
0
    def ventanaVoluntarios(self,row):

        id = -1
        guardar = TRUE
        # Creamos una ventana nueva
        t = Toplevel(self)
        t.wm_title("Crear Voluntario")

        # Etiqueta y entrada de nombre
        Label(t, text="Nombre").grid(row=0)
        entradaNombre = Entry(t)
        entradaNombre.grid(row=0, column=1,sticky = "ew")

        # Etiqueta y entrada de apellidos
        Label(t, text="Apellidos").grid(row=1)
        entradaApellidos = Entry(t)
        entradaApellidos.grid(row=1, column=1,sticky = "ew")

        # Etiqueta y entrada de DNI
        Label(t, text="DNI").grid(row=2)
        entradaDNI = Entry(t)
        entradaDNI.grid(row=2, column=1,sticky = "ew")

        # Etiqueta y entrada de Dirreccion
        Label(t, text="Direccion").grid(row=3)
        entradaDireccion = Entry(t)
        entradaDireccion.grid(row=3, column=1)

        # Etiqueta y seleccion de Estudios
        Label(t, text="Estudios").grid(row=4)
        box_value = StringVar()
        self.getEstudios()
        self.selectorEstudios = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorEstudios['values'] = self.listadoEstudios[0]
        self.selectorEstudios.configure(width=25)
        self.selectorEstudios.current(0)
        self.selectorEstudios.grid(row=4, column=1)

        botonEditarEstudios = Button(t, text="Editar", command=self.editarEstudio)
        botonNuevosEstudios = Button(t, text="Nuevo", command=self.nuevoEstudio)
        botonEditarEstudios.grid(row=4, column=2)
        botonNuevosEstudios.grid(row=4, column=3)

        # Etiqueta y seleccion de Genero
        Label(t, text="Genero").grid(row=5)
        seleccionGenero = Combobox(t, values=["Masculino (M)", "Femenino (F)"], state='readonly')
        seleccionGenero.grid(row=5, column=1)

        # Etiqueta y seleccion de Parroquial
        Label(t, text="Parroquial").grid(row=6)
        box_value = StringVar()
        self.getParroquial()
        self.selectorParroquial = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorParroquial['values'] = self.listadoParroquial[0]
        self.selectorParroquial.configure(width=25)
        self.selectorParroquial.current(0)
        self.selectorParroquial.grid(row=6, column=1)

        botonEditarParroquial = Button(t, text="Editar", command=self.editarParroquia)
        botonNuevaParroqual = Button(t, text="Nuevo", command=self.nuevaParroquia)
        botonEditarParroquial.grid(row=6, column=2)
        botonNuevaParroqual.grid(row=6, column=3)

        # Etiqueta y seleccion de Correo
        Label(t, text="Correo").grid(row=0, column=4)
        entradaCorreo = Entry(t)
        entradaCorreo.grid(row=0, column=5)

        Label(t, text="Telefono 1").grid(row=1, column=4)
        entradaTelefono1 = Entry(t)
        entradaTelefono1.grid(row=1, column=5)

        Label(t, text="Telefono 2").grid(row=2, column=4)
        entradaTelefono2 = Entry(t)
        entradaTelefono2.grid(row=2, column=5)

        # Etiqueta y entrada de Fecha
        Label(t, text="Fecha").grid(row=3, column=4)
        entradaAno = Entry(t)
        entradaMes = Entry(t)
        entradaDia = Entry(t)
        entradaAno.grid(row=3, column=5)
        entradaMes.grid(row=3, column=6)
        entradaDia.grid(row=3, column=7)

        # Etiqueta y seleccion de Pais
        Label(t, text="Pais").grid(row=4, column=4)
        box_value = StringVar()
        self.getPais()
        self.selectorPais = Combobox(t, textvariable=box_value, state='readonly')
        self.selectorPais['values'] = self.listadoPais[0]
        self.selectorPais.configure(width=25)
        self.selectorPais.current(0)
        self.selectorPais.grid(row=4, column=5)

        botonEditarPais = Button(t, text="Editar", command=self.editarPais)
        botonNuevaPais = Button(t, text="Nuevo", command=self.nuevoPais)
        botonEditarPais.grid(row=4, column=6)
        botonNuevaPais.grid(row=4, column=7)

        #Rellenamos los cambos si estamos editando
        if row > -1:
            voluntario = self.table.model.getRecordAtRow(row)
            entradaNombre.insert(END,voluntario['nombre'])
            entradaApellidos.insert(END,voluntario['apellidos'])
            entradaCorreo.insert(END,voluntario['correo_electronico'])
            entradaTelefono1.insert(END,voluntario['telefono_1'])
            entradaTelefono2.insert(END,voluntario['telefono_2'])
            entradaDireccion.insert(END,voluntario['direccion'])
            entradaDNI.insert(END,voluntario['dni'])
            self.selectorEstudios.set(voluntario['estudio'])
            self.selectorParroquial.set(voluntario['parroquial'])
            guardar = FALSE
            id = voluntario['id']





        button5 = Button(t, text="Guardar", command=lambda: self.nuevoVoluntario(entradaNombre.get(),
                                                                                 entradaApellidos.get(),entradaDNI.get(),entradaDireccion.get(),
                                                                                 entradaCorreo.get(),1,self.listadoEstudios[1][self.selectorEstudios.current()],
                                                                                 self.listadoParroquial[1][self.selectorParroquial.current()],
                                                                                 1,entradaTelefono1.get(),entradaTelefono2.get(),"M","2001-01-01",t,guardar,id))
        button6 = Button(t, text="Cancelar", command=t.destroy)

        button5.grid(row=7, column=4)
        button6.grid(row=7, column=5)
Exemplo n.º 37
0
    def openCmdWindow(self):
        """
        open the cmd window and initial all the button and text
        """
        panel = Toplevel(self.root)
        panel.wm_title("Command Panel")

        # create text input entry
        text0 = tki.Label(
            panel,
            text=
            'This Controller map keyboard inputs to Tello control commands\n'
            'Adjust the trackbar to reset distance and degree parameter',
            font='Helvetica 10 bold')
        text0.pack(side='top')

        text1 = tki.Label(
            panel,
            text='W - Move Tello Up\t\t\tArrow Up - Move Tello Forward\n'
            'S - Move Tello Down\t\t\tArrow Down - Move Tello Backward\n'
            'A - Rotate Tello Counter-Clockwise\tArrow Left - Move Tello Left\n'
            'D - Rotate Tello Clockwise\t\tArrow Right - Move Tello Right',
            justify="left")
        text1.pack(side="top")

        self.btn_landing = tki.Button(panel,
                                      text="Land",
                                      relief="raised",
                                      command=self.telloLanding)
        self.btn_landing.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        self.btn_takeoff = tki.Button(panel,
                                      text="Takeoff",
                                      relief="raised",
                                      command=self.telloTakeOff)
        self.btn_takeoff.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        # binding arrow keys to drone control
        self.tmp_f = tki.Frame(panel, width=100, height=2)
        self.tmp_f.bind('<KeyPress-w>', self.on_keypress_w)
        self.tmp_f.bind('<KeyPress-s>', self.on_keypress_s)
        self.tmp_f.bind('<KeyPress-a>', self.on_keypress_a)
        self.tmp_f.bind('<KeyPress-d>', self.on_keypress_d)
        self.tmp_f.bind('<KeyPress-Up>', self.on_keypress_up)
        self.tmp_f.bind('<KeyPress-Down>', self.on_keypress_down)
        self.tmp_f.bind('<KeyPress-Left>', self.on_keypress_left)
        self.tmp_f.bind('<KeyPress-Right>', self.on_keypress_right)
        self.tmp_f.pack(side="bottom")
        self.tmp_f.focus_set()

        self.btn_landing = tki.Button(panel,
                                      text="Flip",
                                      relief="raised",
                                      command=self.openFlipWindow)
        self.btn_landing.pack(side="bottom",
                              fill="both",
                              expand="yes",
                              padx=10,
                              pady=5)

        self.distance_bar = Scale(panel,
                                  from_=0.02,
                                  to=5,
                                  tickinterval=0.01,
                                  digits=3,
                                  label='Distance(m)',
                                  resolution=0.01)
        self.distance_bar.set(0.2)
        self.distance_bar.pack(side="left")

        self.btn_distance = tki.Button(
            panel,
            text="Reset Distance",
            relief="raised",
            command=self.updateDistancebar,
        )
        self.btn_distance.pack(side="left",
                               fill="both",
                               expand="yes",
                               padx=10,
                               pady=5)

        self.degree_bar = Scale(panel,
                                from_=1,
                                to=360,
                                tickinterval=10,
                                label='Degree')
        self.degree_bar.set(30)
        self.degree_bar.pack(side="right")

        self.btn_distance = tki.Button(
            panel,
            text="Reset Degreejustin bieber love yourself",
            relief="raised",
            command=self.updateDegreebar)
        self.btn_distance.pack(side="right",
                               fill="both",
                               expand="yes",
                               padx=10,
                               pady=5)
Exemplo n.º 38
0
class Beings:
    def __init__(self, main): # cnfbtn, world, predCount, preyCount, sbtn, bbox, bbox1, timelbl, main):
        '''args world (eg Canvas object), predCount and preyCount, initiates life process when live is called in pain loop
        '''
        self.world = main.world
        self.world.state = {'state' : 'inactive'}
        self.main = main

        #get configuration
        self.config = WorldConfiguration()

        self.deadPredators = list()
        self.deadPrey = list()

        self.tags = list()

        #stop button and being box for binding after live() is called 
        self.sbtn = main.sbtn
        self.bbox = main.bbox
        self.bbox1 = main.bbox1
        self.timelbl = main.timelbl


    def configure(self):
        self.conf = Toplevel()
        self.conf.wm_title("Configure Universe")

        self.reconfig = self.config.reconfigure(self)


    def live(self):
        #set the state to active and clear the canvas of all attributes
        self.predators = [Predator(self) for i in range(self.config.predCount)]
        self.prey = [Prey(self) for i in range(self.config.preyCount)]
        self.beings = list(self.predators + self.prey)
     
        
        self.world.state['state'] = 'active'
        self.world.delete("all")

        for being in self.beings:
            if being.type == 'predator':
                being.tag = self.world.create_rectangle(being.genX, being.genY, being.genX+10, being.genY-10, fill=being.color)
            else:
                being.tag = self.world.create_oval(being.genX, being.genY, being.genX+10, being.genY-10, fill=being.color)
        
        
        #start session thread
        self.stopThread = False
        self.session = Thread(target=self.activate)
        self.session.start()

        #bind the Thread object _Thread__stop() method to the stop button
        self.sbtn.config(command=self.threadStop)
        

    def threadStop(self):
        self.stopThread = True
        self.session = None


    def activate(self):
        #instantiate timer and pass in timerlbl
        self.timer = Timer(self.timelbl)
        
        #bind showInfo to each being
        lambda x: self.world.tag_bind(x.tag,"<ButtonPress-1>", x.showInfo), self.beings

        while self.stopThread == False:
            #move each being
            map(lambda x: self.move(x), self.beings)
           
            #predators hunt!
            for pred in self.predators:
                pred.hunt(self.prey, self.world, self)
                pred.kill(self.world, self.prey, self.deadPrey, self.beings) 
            
            #age the beings
            for being in self.beings:
                being.age(self)

            #update the clock
            self.timer.updateClock()

            #update being box
            self.bbox.delete(1.0, END)
            bboxstr = "Predators \n"
            for pred in self.predators:
                if pred.target:
                    bboxstr += "tag-%s; vR-%s; kR-%s; kC-%s; lfe-%s tgt-%s\n" % (pred.tag, pred.visionRange, pred.killRange, pred.killCount, pred.curLife, pred.target.tag) 
                else:
                    bboxstr += "tag-%s; vR-%s; kR-%s; kC-%s; lfe-%s tgt-%s\n" % (pred.tag, pred.visionRange, pred.killRange, pred.killCount, pred.curLife, "None")
            bboxstr += "#pred-%s  #prey-%s #beings=%s\nDead Predators:\n" % (len(self.predators), len(self.prey), len(self.beings))
            for pred in self.deadPredators:
                bboxstr += "tag-%s; vR-%s, kR-%s; kC-%s\n" % (pred.tag, pred.visionRange, pred.killRange, pred.killCount)    
            self.bbox.insert("1.0", bboxstr)

            #check to ensure game is not over
            if len(self.predators) == 0 or len(self.prey) == 0:
                self.threadStop()

            #sleep to avoid stack overflow
            sleep(.1)
            
    def move(self, being):
        '''
        Receives a predator or prey object and gives it a new set of position attributes
        '''
        #refresh being coors
        being.curX0, being.curY0, being.curX1, being.curY1 = self.world.coords(being.tag)[0], self.world.coords(being.tag)[1], self.world.coords(being.tag)[2], self.world.coords(being.tag)[3]

        #if N, decrease Y by speed coef and ensure being isn't above N world boundary
        if directionMap[being.direction] == 'N':
            being.curY = self.world.coords(being.tag)[1]
            being.offset = -1 * (being.speed)
            if being.curY < 35:
                being.offset = (being.speed) / 2 # being.genY + (being.genY - self.world.winfo_height())
        #if S, increase Y by speed coef and check to see if it is below the bottom world boudary 
        elif directionMap[being.direction] == 'S':
            being.curY = self.world.coords(being.tag)[1]
            being.offset = being.speed 
            if being.curY > self.world.winfo_height()-5:
                being.offset = (-1 * (being.speed))/2 #being.genY - (self.world.winfo_height()-being.genY)
        #if E decrease X by speed coef and ensure not outside E world boundary
        elif directionMap[being.direction] == 'E':
            being.curX = self.world.coords(being.tag)[0]
            being.offset = being.speed
            if being.curX > self.world.winfo_width()-5:
                being.offset = (-1 * (being.speed) / 2)
        #if W increase X by speed coef and ensure not outside W world boundary
        elif directionMap[being.direction] == 'W':
            being.curX = self.world.coords(being.tag)[0]
            being.offset = -1 * (being.speed)
            if being.curX < 15:
                being.offset = (being.speed) / 2 # being.genX + (being.genX - self.world.winfo_width())

        #move the being to the new coords
        if directionMap[being.direction] in ['N','S']:
           self.world.move(being.tag, 0, being.offset)
        elif directionMap[being.direction] in ['E','W']:
           self.world.move(being.tag, being.offset, 0)
        
        #randomize being vector if idle
        if being.state == 'idle':
            being.direction = np.random.randint(4)
        if being.type == 'prey':
            being.direction = np.random.randint(4)
        if being.type =='predator':
            if being.target == None:
                being.direction = np.random.randint(4)

    #take one step forward (in dev)
    def walk(self):
        for pred in self.predators:
            self.move(pred)
        for prey in self.prey:
            self.move(prey)
Exemplo n.º 39
0
def Delete_click(root, Listbox):
    if (Listbox.curselection() != ()):
        root.grab_release()
        print("Delete click")
        popup = Toplevel()
        popup.resizable(False, False)
        popup.geometry("200x100+700+300")
        popup.grab_set()

        def Cancle():
            popup.grab_release()
            root.grab_set()
            popup.destroy()

        def OK(Listbox):
            print('feature_support.OK_click')

            newrow = []
            selected = Listbox.get(ACTIVE)
            os.remove("./data/%s.mp3" % selected.split(' ----- ')[1])
            for line in fileinput.input("./data/database.csv", inplace=True):
                if line == '\n':
                    continue
                if int(line[0]) < int(selected[0]):
                    print line,
                if int(line[0]) > int(selected[0]):
                    newline = line.split()
                    newline[0] = str(int(newline[0]) - 1)
                    print " ".join(newline)
                    print '\n',
            fileinput.close()
            with open('./data/list_person.txt', 'rb') as lpfile:
                row_count = sum(1 for row in lpfile)
            os.remove('./model/net%d.xml' % int(selected[0]))
            if (row_count > 1) or (int(selected[0]) != row_count):
                for i in range(int(selected[0]) + 1, row_count + 1):
                    os.rename('./model/net%d.xml' % i,
                              './model/net%d.xml' % (i - 1))
            with open('./data/list_person.txt', 'rb') as lpfile:
                for row in lpfile:
                    if (row != []):
                        row = row.split()
                        if (int(row[0]) < int(selected[0])):
                            newrow.append(row)
                        if (int(row[0]) > int(selected[0])):
                            row[0] = int(row[0]) - 1
                            newrow.append(row)
            Listbox.delete(0, END)
            with open('./data/list_person.txt', 'wb') as lpfile:
                i = 0
                for row in newrow:
                    Listbox.insert(i, "%d ----- %s" % (int(row[0]), row[1]))
                    lpfile.write("%s %s\n" % (row[0], row[1]))
                    i += 1
            NeuralNetwork.remove_model(int(selected[0]))
            popup.destroy()
            root.grab_set()

        popup.wm_title("Delete")
        l1 = Label(popup, text="Bạn có muốn xóa !")
        b1 = Button(popup, text="OK", width=7, command=lambda: OK(Listbox))
        b2 = Button(popup, text="Cancle", width=7, command=Cancle)
        l1.place(relx=0.25, rely=0.2)
        b1.place(relx=0.18, rely=0.6)
        b2.place(relx=0.52, rely=0.6)
        popup.mainloop()
    else:
        tkMessageBox.showinfo("Error", "Vui lòng chọn đối tượng")
Exemplo n.º 40
0
    l.grid(row=1, column=0)
    e = Entry(root)
    e.grid(row=1, column=1)

    create_buddy(l,e)

    def login():
        showinfo("Login","Executed login callback")
    
    button = Button(root, text="Log in", command=login, underline=0)
    button.grid(row=2, column=0)
    
    create_shortcut_to_button(button)

    dialog = Toplevel(root)
    dialog.wm_title("Sign up")

    l= Label(dialog, text="Name:", underline=0)
    l.grid(row=0, column=0)
    e = Entry(dialog)
    e.grid(row=0, column=1)

    create_buddy(l,e)

    l= Label(dialog, text="Address:", underline=0)
    l.grid(row=1, column=0)
    e = Entry(dialog)
    e.grid(row=1, column=1)
    
    create_buddy(l,e)
    
Exemplo n.º 41
0
class ContinuousTMPViewer(object):
    def __init__(self,
                 regions,
                 tl_x=0,
                 tl_y=0,
                 width=500,
                 height=250,
                 title='Grid',
                 background='tan'):
        self.tk = Tk()
        # tk.geometry('%dx%d+%d+%d'%(width, height, 100, 0))
        self.tk.withdraw()
        self.top = Toplevel(self.tk)
        self.top.wm_title(title)
        self.top.protocol('WM_DELETE_WINDOW', self.top.destroy)

        self.regions = regions
        self.tl_x = tl_x
        self.tl_y = tl_y
        self.width = width
        self.height = height
        self.canvas = Canvas(self.top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()
        # self.center()
        self.move_frame(self.tl_x, self.tl_y)

        self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER) / get_width(
            regions[GROUND])  # Maintains aspect ratio
        self.dist_width = self.width / self.dist_to_pixel
        self.dist_height = self.height / self.dist_to_pixel
        self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT
        self.robot_dist = self.dist_height / 2.

        self.robot = []
        self.blocks = []
        self.holding = None
        self.environment = []
        self.draw_environment()

    def center(self):
        self.top.update_idletasks()
        w = self.top.winfo_screenwidth()
        h = self.top.winfo_screenheight()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        x = w / 2 - size[0] / 2
        y = h / 2 - size[1] / 2
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def move_frame(self, x, y):
        self.top.update_idletasks()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def scale_x(self, x):  # x \in [-self.dist_width/2, self.dist_width/2]
        return self.dist_to_pixel * (x + self.dist_width / 2.)

    def scale_y(self, y):  # y \in [0, self.dist_height]
        return self.ground_height - self.dist_to_pixel * y

    def draw_block(self, x, width, height, color='blue'):
        self.blocks.append(
            self.canvas.create_rectangle(self.scale_x(x - width / 2.),
                                         self.scale_y(0),
                                         self.scale_x(x + width / 2.),
                                         self.scale_y(height),
                                         fill=color,
                                         outline='black',
                                         width=2))

    # def draw_holding(self, x, width, height, color='blue'):
    #     self.holding = self.canvas.create_rectangle(self.scale_x(x - width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2 - height),
    #                                                 self.scale_x(x + width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2),
    #                                                 fill=color, outline='black', width=2)

    def draw_region(self, region, color='red'):
        x1, x2 = map(self.scale_x, region)
        self.environment.append(
            self.canvas.create_rectangle(x1,
                                         self.ground_height,
                                         x2,
                                         self.height,
                                         fill=color,
                                         outline='black',
                                         width=2))

    def draw_environment(self, table_color='lightgrey'):
        self.environment = []
        self.draw_region(self.regions[GROUND], color=table_color)
        for name, region in self.regions.items():
            if name != GROUND:
                self.draw_region(region)

    def draw_robot(
        self,
        x,
        y,
        color='yellow'
    ):  # TODO - could also visualize as top grasps instead of side grasps
        #y = self.robot_dist
        self.robot = [
            self.canvas.create_rectangle(self.scale_x(x - SUCTION_WIDTH / 2.),
                                         self.scale_y(y - SUCTION_HEIGHT / 2.),
                                         self.scale_x(x + SUCTION_WIDTH / 2.),
                                         self.scale_y(y + SUCTION_HEIGHT / 2.),
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_rectangle(self.scale_x(x - STEM_WIDTH / 2.),
                                         self.scale_y(y + SUCTION_HEIGHT / 2.),
                                         self.scale_x(x + STEM_WIDTH / 2.),
                                         self.scale_y(y + SUCTION_HEIGHT / 2. +
                                                      STEM_HEIGHT),
                                         fill=color,
                                         outline='black',
                                         width=2),
        ]

    def clear_state(self):
        for block in self.blocks:
            self.canvas.delete(block)
        for part in self.robot:
            self.canvas.delete(part)
        if self.holding is not None:
            self.canvas.delete(self.holding)

    def clear_all(self):
        self.canvas.delete('all')

    def save(self, filename):
        # self.canvas.postscript(file='%s.ps'%filename, colormode='color')
        from PIL import ImageGrab
        ImageGrab.grab((0, 0, self.width, self.height)).save(filename + '.jpg')
class InstructionsFrame(Frame):
    def __init__(self, parent, width=500, height=200, background="white"):
        Frame.__init__(self, parent)
        self.initialize()

    def initialize(self):
        self.instructions_text = \
    """
    Seating Chart Creator makes an optimal seating chart for a given set of people, tables, and days. It generates a preliminary chart, then searches for a better one by switching people around.\n"""
        self.instructions_label = Label(self, text=self.instructions_text,
                                        font=("Optima", 14), anchor=W,
                                        justify=LEFT)
        self.instructions_label.grid(row=0, column=0, sticky=(W))

        miniframe = Frame(self)
        miniframe.grid(row=1, column=0, padx=0, pady=(0, 20))
        self.rules_button = Button(miniframe,
                                   text="View list of optimization rules",
                                   command=self.show_rules)
        self.rules_button.grid(row=1, column=0, sticky=(W), padx=10)

        self.people_example = Button(miniframe,
                                     text="View example people input file",
                                     command=self.show_people_example)
        self.people_example.grid(row=1, column=1, sticky=(W), padx=10)

        self.tables_example = Button(miniframe,
                                     text="View example tables input file",
                                     command=self.show_tables_example)
        self.tables_example.grid(row=1, column=2, sticky=(W), padx=10)

    def show_rules(self):
        self.windowr = Toplevel(self)
        self.windowr.wm_title("Optimization Rules")
        self.windowr.rowconfigure(0, weight=1)
        self.windowr.rowconfigure(1, weight=1)
        self.windowr.columnconfigure(0, weight=1)

        innerwindowr = Canvas(self.windowr)
        innerwindowr.pack()
        myscrollbar=Scrollbar(self.windowr, orient="vertical",
                              command=innerwindowr.yview)
        innerwindowr.configure(yscrollcommand=myscrollbar.set)
        myscrollbar.pack(side="right",fill="y")

        #self.rtitle_label2 = Label(z,
        #                           text="Seating Chart Creator's Optimization Rules",
        #                           font=("Optima Italic", 24))
        #self.rtitle_label2.pack()

        rtext1 = \
"""
*** Seating Chart Creator's Optimization Rules ***

Depending on the input data, it may or may not be possible to create a perfect seating
chart. Even if there is a perfect solution, there is no fast or easy way to find it.

Seating Chart Creator searches for that perfect solution using an optimization algorithm.
It specifies the criteria to evaluate the solution with, then searches for the
solution that best meets that criteria.

The search process involves random factors, so if you run it multiple times, you will
get different answers.


*** The Criteria ***

SCC looks for a solution with the lowest 'cost'. The cost of a solution is determined by:

* The number of people sitting in the same spot multiple times.
* The number of pairs sitting together multiple times.
* The number of trios sitting together multiple times.
* The distance of each table from its optimal category balance.

The table sizes always correspond with those in the input file.


*** The Process ***

Step 1: Building the First Guess

SCC loops through the days of the event. On each day, it considers each person individually
and places him or her in the best spot available. People are shuffled each round so that
no one consistently gets the 'last pick' of the tables.

When considering where to seat a person, the following tables are excluded:
- Tables that are already full
- Tables that already have enough people of the same category as the person to be seated.

The person is then assigned to the table with the fewest people he/she has already sat with.


Step 2: Switching People Around

The strategy above is fairly good, but not perfect. SCC uses it as a starting point,
then generates new solutions by repeatedly switching individuals. The 'cost' is
calculated for each new solution. If a new solution is better than the current solution,
it is used as the starting point for the next round.

The technique SCC uses is called 'simulated annealing'. It is a frequently-used and
highly-regarded method for solving problems like this one. However, it is not guaranteed
to find a perfect solution.

The switching steps take a very long time (minutes - hours) because of the computational
complexity of counting the number of times everyone sits together.

"""
        #scrollbar = Scrollbar(innerwindowr)
        #scrollbar.pack(side=RIGHT, fill=Y)
        #self.foo = Label(innerwindowr, text=rtext1)
        self.rules_text_box = Text(innerwindowr, width=100)
        self.rules_text_box.insert(INSERT, rtext1)
        self.rules_text_box.config(highlightthickness=0)
        self.rules_text_box.pack(padx=20)
        #self.foo.config(yscrollcommand=scrollbar.set)
        #scrollbar.config(command=self.foo.yview)

    def show_people_example(self):
        self.window = Toplevel(self)
        self.window.wm_title = "People Example"
        self.window.rowconfigure(0, weight=1)
        self.window.rowconfigure(1, weight=1)
        self.window.columnconfigure(0, weight=1)

        innerwindowp = Frame(self.window)
        innerwindowp.grid(row=0, column=0)
        self.ptitle_label2 = Label(innerwindowp,
                                   text="Example People Input File",
                                   font=("Optima Italic", 24))
        self.ptitle_label2.grid(row=0, column=0)
        ptext1 = \
"""
The 'People' input file contains information about the people to be seated and where they might have been preassigned to sit.
It should be saved in CSV format."""
        pheader1 = "COLUMN NAMES"
        ptext2 = \
"""The file should contain the column headers 'First Name', 'Last Name', and 'Category', written exactly as printed here -
capitalization is important.

All other columns are assumed to be the names of the days you are making the chart for. They must match the days in your
'Tables' input file exactly (again, capitalization is important)."""
        pheader2 = "NOTES"
        ptext3 = \
"""Each person should be assigned a category. You can name the categories whatever you like.

If a person has been preassigned to the head table on a particular day, write 'Head' (with a capital 'H') in the corresponding
cell."""
        ptext1label = Label(innerwindowp, text=ptext1, justify=LEFT)
        ptext1label.grid(row=1, column=0, padx=20, sticky=(W))

        pheader1label = Label(innerwindowp, text=pheader1,
                              font=("Optima Italic", 14), justify=LEFT)
        pheader1label.grid(row=2, column=0, padx=20, pady=(20, 0), sticky=(W))

        ptext2label = Label(innerwindowp, text=ptext2, justify=LEFT)
        ptext2label.grid(row=3, column=0, padx=20, sticky=(W))

        pheader2label = Label(innerwindowp, text=pheader2,
                              font=("Optima Italic", 14), justify=LEFT)
        pheader2label.grid(row=4, column=0, padx=20, pady=(20,0), sticky=(W))

        ptext3label = Label(innerwindowp, text=ptext3, justify=LEFT)
        ptext3label.grid(row=5, column=0, padx=20, sticky=(W))

        self.picture2p = PhotoImage(file=find_data_file('static/people-example.gif'))
        self.picture_label2p = Label(self.window, image = self.picture2p)
        self.picture_label2p.grid(row=2, column=0)

    def show_tables_example(self):
        self.window2 = Toplevel(self)
        self.window2.wm_title = "Tables Example"
        self.window2.rowconfigure(0, weight=1)
        self.window2.rowconfigure(1, weight=1)
        self.window2.columnconfigure(0, weight=1)

        innerwindow = Frame(self.window2)
        innerwindow.grid(row=0, column=0)
        self.title_label2 = Label(innerwindow,
                                  text="Example Tables Input File",
                                  font=("Optima Italic", 24))
        self.title_label2.grid(row=0, column=0)
        text1 = \
"""
The 'Tables' input file contains information about the individual tables' names and capacities. It should be saved in CSV
format."""
        header1 = "COLUMN NAMES"
        text2 = \
"""The file should contain the column header 'Table Name', written exactly as printed here - capitalization is important.

All other columns are assumed to be the names of the days you are making the chart for. They must match the days in your
'People' input file exactly (again, capitalization is important)."""
        header2 = "NOTES"
        text3= \
"""You can choose arbitrary table names. If you include a table named 'Head', it will be populated exclusively with the people
preassigned to it in the 'People' input file.

The number in each cell represents the table's capacity on that day. Make sure the overall capacity is at least as great as
the number of people to be seated!"""
        text1label = Label(innerwindow, text=text1, justify=LEFT)
        text1label.grid(row=1, column=0, padx=20, sticky=(W))

        header1label = Label(innerwindow, text=header1,
                             font=("Optima Italic", 14), justify=LEFT)
        header1label.grid(row=2, column=0, padx=20, pady=(20, 0), sticky=(W))

        text2label = Label(innerwindow, text=text2, justify=LEFT)
        text2label.grid(row=3, column=0, padx=20, sticky=(W))

        header2label = Label(innerwindow, text=header2,
                             font=("Optima Italic", 14), justify=LEFT)
        header2label.grid(row=4, column=0, padx=20, pady=(20, 0), sticky=(W))

        text3label = Label(innerwindow, text=text3, justify=LEFT)
        text3label.grid(row=5, column=0, padx=20, sticky=(W))

        self.picture2 = PhotoImage(file=find_data_file('static/tables-example.gif'))
        self.picture_label2 = Label(self.window2, image=self.picture2)
        self.picture_label2.grid(row=2, column=0)
Exemplo n.º 43
0
class ContinuousTMPViewer(object):
    def __init__(self,
                 suction_height,
                 regions,
                 tl_x=0,
                 tl_y=0,
                 width=500,
                 height=150,
                 title='Grid',
                 background='tan'):
        self.tk = Tk()
        # tk.geometry('%dx%d+%d+%d'%(width, height, 100, 0))
        self.tk.withdraw()
        self.top = Toplevel(self.tk)
        self.top.wm_title(title)
        self.top.protocol('WM_DELETE_WINDOW', self.top.destroy)

        self.suction_height = suction_height
        self.regions = regions
        self.tl_x = tl_x
        self.tl_y = tl_y
        self.width = width
        self.height = height
        self.canvas = Canvas(self.top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()
        # self.center()
        self.move_frame(self.tl_x, self.tl_y)

        max_width = max(
            map(get_width,
                regions.values()))  # Really should take width of max minus min
        self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER
                              ) / max_width  # Maintains aspect ratio
        self.dist_width = self.width / self.dist_to_pixel
        self.dist_height = self.height / self.dist_to_pixel
        self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT
        self.robot_dist = self.dist_height / 2.

        self.robot = []
        self.blocks = []
        self.holding = None
        self.environment = []
        self.draw_environment()

    def center(self):
        self.top.update_idletasks()
        w = self.top.winfo_screenwidth()
        h = self.top.winfo_screenheight()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        x = w / 2 - size[0] / 2
        y = h / 2 - size[1] / 2
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def move_frame(self, x, y):
        self.top.update_idletasks()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def scale_x(self, x):  # x \in [-self.dist_width/2, self.dist_width/2]
        return self.dist_to_pixel * (x + self.dist_width / 2.)

    def scale_y(self, y):  # y \in [0, self.dist_height]
        return self.ground_height - self.dist_to_pixel * y

    def draw_block(self, x, y, width, height, name='', color='blue'):
        self.blocks.extend([
            self.canvas.create_rectangle(self.scale_x(x - width / 2.),
                                         self.scale_y(y),
                                         self.scale_x(x + width / 2.),
                                         self.scale_y(y + height),
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text(self.scale_x(x),
                                    self.scale_y(y + height / 2),
                                    text=name),
        ])

    # def draw_holding(self, x, width, height, color='blue'):
    #     self.holding = self.canvas.create_rectangle(self.scale_x(x - width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2 - height),
    #                                                 self.scale_x(x + width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2),
    #                                                 fill=color, outline='black', width=2)

    def draw_region(self, region, name='', color='red'):
        x1, x2 = map(self.scale_x, region)
        y1, y2 = self.ground_height, self.height
        self.environment.extend([
            self.canvas.create_rectangle(x1,
                                         y1,
                                         x2,
                                         y2,
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=name),
        ])

    def draw_environment(self):
        # TODO: automatically draw in order
        self.environment = []
        for name, region in sorted(self.regions.items(),
                                   key=lambda pair: get_width(pair[1]),
                                   reverse=True):
            self.draw_region(region, name=name, color=name)

    def draw_robot(
        self,
        x,
        y,
        color='yellow'
    ):  # TODO - could also visualize as top grasps instead of side grasps
        #y = self.robot_dist
        self.robot = [
            self.canvas.create_rectangle(
                self.scale_x(x - SUCTION_WIDTH / 2.),
                self.scale_y(y - self.suction_height / 2.),
                self.scale_x(x + SUCTION_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2.),
                fill=color,
                outline='black',
                width=2),
            self.canvas.create_rectangle(
                self.scale_x(x - STEM_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2.),
                self.scale_x(x + STEM_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2. + STEM_HEIGHT),
                fill=color,
                outline='black',
                width=2),
        ]

    def clear_state(self):
        for block in self.blocks:
            self.canvas.delete(block)
        for part in self.robot:
            self.canvas.delete(part)
        if self.holding is not None:
            self.canvas.delete(self.holding)

    def clear_all(self):
        self.canvas.delete('all')

    def save(self, filename):
        # TODO: screen recording based on location like I did before
        # TODO: only works on windows
        # self.canvas.postscript(file='%s.ps'%filename, colormode='color')
        #from PIL import ImageGrab
        try:
            import pyscreenshot as ImageGrab
        except ImportError:
            return None
        x, y = self.top.winfo_x(), 2 * self.top.winfo_y()
        width, height = self.top.winfo_width(), self.top.winfo_height(
        )  # winfo_width, winfo_reqheight
        path = filename + '.png'
        ImageGrab.grab((x, y, x + width, y + height)).save(path)
        return path
Exemplo n.º 44
0
class Evolution(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def configure(self):
        self.conf = Toplevel(self)
        self.conf.wm_title("Configure Universe")

        self.wc.reconfigure(self)

    def initUI(self):
        #create initial Beings object (not instantiated until live is called)
        self.wc = WorldConfiguration()

        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(2, weight=1)
        self.columnconfigure(4, pad=7)
        self.rowconfigure(3, weight=1)

        lbl = Label(self, text="PyLife")
        lbl.grid(sticky=W, padx=25, pady=5)

        self.world = Canvas(self, background="#7474DB")
        self.world.grid(row=1,
                        column=0,
                        columnspan=3,
                        rowspan=8,
                        padx=5,
                        sticky=E + W + N + S)

        self.sbtn = Button(self, text="Stop")
        self.sbtn.grid(row=1, column=4, pady=5, sticky=E)

        self.bbox = Text(self, height=20, width=36)
        self.bbox.grid(row=3, column=4, padx=5, sticky=E + W + N + S)

        self.bbox1 = Text(self, height=11, width=36)
        self.bbox1.grid(row=4, column=4, padx=5, sticky=E + W + N + S)

        self.cbtn = Button(self, text="Close", command=self.parent.destroy)
        self.cbtn.grid(row=9, column=4, pady=5)

        self.cnfbtn = Button(self, text="Configure Universe")
        self.cnfbtn.grid(row=9, column=0, padx=5)

        self.timelbl = Text(self, height=1, width=10)
        self.timelbl.grid(row=2, column=4, pady=5)

        b = Beings(self)
        abtn = Button(
            self, text="Start", command=b.live
        )  #Beings(cnfbtn, world, 4, 10, sbtn, bbox, bbox1, timelbl).live)
        abtn.grid(row=1, column=4, pady=5, sticky=W)

        self.cnfbtn.config(command=b.configure)

    def close(self):
        self.parent.destroy