Exemple #1
0
class NumWindow(Toplevel):
	def __init__(self, master, title, binder, geometry):
		Toplevel.__init__(self, master)

		self.master = master
		self.binder = binder
		self.initUI(title, geometry)
	
	def initUI(self, title, geometry):
		self.title(title)
		self.geometry(geometry)

		def nothing():
			pass

		self.protocol('WM_DELETE_WINDOW', nothing)

		self.bind('<Key>', self.binder.keyEvent)
		self.label = Label(self, text='-', background='white')
		self.label.pack(fill=BOTH, expand=1)

		def resize(event):
			self.label.config(font=(None, int(event.height * .95)))

		self.bind('<Configure>', resize)

	def setNum(self, num):
		self.label.config(text=num)
Exemple #2
0
    def append_chords(self, chords=[]):
        '''pass a [list] of Chords to the Accordion object'''

        self.update_idletasks()
        row = 0
        width = max([c.winfo_reqwidth() for c in chords])
        
        for c in chords:
            i = PhotoImage() # blank image to force Label to use pixel size
            label = Label(self, text=c.title,
                          image=i,
                          compound='center',
                          width=width,
                          bg=self.style['title_bg'],
                          fg=self.style['title_fg'],
                          bd=2, relief='groove')
            
            label.grid(row=row, column=0)
            c.grid(row=row+1, column=0, sticky='nsew')
            c.grid_remove()
            row += 2
            
            label.bind('<Button-1>', lambda e,
                       c=c: self._click_handler(c))
            label.bind('<Enter>', lambda e,
                       label=label, i=i: label.config(bg=self.style['highlight']))
            label.bind('<Leave>', lambda e,
                       label=label, i=i: label.config(bg=self.style['title_bg']))
 def show(text, background="#fff", timeout_ms=DEFAULT_TIMEOUT, font_size=100):
     root = Tk()
     root.attributes("-topmost", True)
     root.lift()
     # Set Timeout
     root.after(timeout_ms, root.destroy)
     # Create Frame
     frame = Frame(root)
     frame.pack(side=TOP, fill=BOTH, expand=YES)
     # Set frame size and position
     screen_width = frame.master.winfo_screenwidth()
     screen_heigh = frame.master.winfo_screenheight()
     w = screen_width * 0.8
     h = screen_heigh * 0.6
     # Center the window
     x = (screen_width/2) - (w/2)
     y = (screen_heigh/2) - (h/2)
     frame.master.geometry('%dx%d+%d+%d' % (w, h, x, y))
     # Adjust frame properties
     frame.master.overrideredirect(True)  # Set no border or title
     frame.config(bg=background)
     # Create text label
     label = Label(frame, text=text, wraplength=screen_width * 0.8)
     label.pack(side=TOP, expand=YES)
     label.config(bg=background, justify=CENTER, font=("calibri", font_size))
     # Set transparency
     root.wait_visibility(root)  # Needed for linux (and must come after overrideredirect)
     root.attributes('-alpha', 0.6)
     # Run Event loop
     root.mainloop()
 def initUI(self):
     #top frame using all the remaining space
     innerTopFrame = Frame(self, background="black")
     innerTopFrame.pack(fill=BOTH, expand=1)
     #CLOSE Label
     innerBottomLeftFrame = Frame(self, background="black")
     innerBottomLeftFrame.place(x=0, width=self.wRoot/2, 
         y=self.hRoot-200, height=200)
     closeLabel = Label(innerBottomLeftFrame, bg="black", fg="black",
         text="CLOSE", font=("Comic Sans MS", 48, "bold"))
     innerBottomLeftFrame.bind("<Enter>", lambda f: closeLabel.config(fg="white"))
     innerBottomLeftFrame.bind("<Leave>", lambda f: closeLabel.config(fg="black"))
     innerBottomLeftFrame.bind("<Button-1>", lambda f: self.root.quit())
     closeLabel.bind("<Button-1>", lambda f: self.root.quit())
     closeLabel.pack(fill=BOTH)
     #SHUT DOWN Label
     innerBottomRightFrame = Frame(self, background="black")
     innerBottomRightFrame.place(x=self.wRoot/2, width=self.wRoot/2, 
         y=self.hRoot-200, height=200)
     shutdownLabel = Label(innerBottomRightFrame, bg="black", fg="black",
         text="SHUT DOWN", font=("Comic Sans MS", 48, "bold"))
     innerBottomRightFrame.bind("<Enter>", lambda f: shutdownLabel.config(fg="white"))
     innerBottomRightFrame.bind("<Leave>", lambda f: shutdownLabel.config(fg="black"))
     innerBottomRightFrame.bind("<Button-1>", self.shutdown)
     shutdownLabel.bind("<Button-1>", self.shutdown)
     shutdownLabel.pack(fill=BOTH)
     #design the FullScreenApp
     self.pack(fill=BOTH, expand=1)
class ImageView(Frame):
    def __init__(self, root, rli):
        Frame.__init__(self, root)
        self.rli = rli
        self.envName = ''
        self.envPlatRow = -1
        self.envPlatCol = -1
        self.envPlatDir = -1
        self.label = Label(self)
        self.label.pack()
        self.view = Label(self)
        self.view.pack()

    def setImage(self, imageName):
        size = self.winfo_width()*9/10
        image = Image.open(imageName)
        image = image.resize((size,size))
        self.photo = PhotoImage(image)
        self.label.config(text=imageName)
        self.view.config(image = self.photo)

    def redraw(self):
        envName = self.rli.env.name
        if envName[-1] in '0123456789': envName = envName[:-1]
        envRow,envCol = self.rli.env.curr_pos
        envFace = self.rli.env.curr_face
        envPlatRow,envPlatCol,envPlatDir = self.rli.env.pomdp.coords2plat(envRow,envCol,envFace)
        if ((self.envName,self.envPlatRow, self.envPlatCol, self.envPlatDir)
            != (envName,envPlatRow,envPlatCol,envPlatDir)):
            self.setImage('%s/Direction%s_%d_%d_%d.jpg' %
                          (self.rli.env.pomdp.map_dir,envName,envPlatRow,envPlatCol,envPlatDir))
            self.envName = envName
            self.envPlatRow = envPlatRow
            self.envPlatCol = envPlatCol
            self.envPlatDir = envPlatDir
class HiddenNeuronNumber(Frame):
    def __init__(self, parent, layer_id):
        Frame.__init__(self, parent)
        self.parent = parent
        
        # Layer id is a number in range(MAX_NUMBER_OF_HIDDEN_LAYERS)
        self.layer_id = layer_id
        
        label_text = 'Neurons for layer {0}: '.format(layer_id + 1)
        self.label = Label(self, text = label_text)
        self.label.grid(row=0, column=0)
         
        
        number_options = range(1, MAX_NEURON_NUMBER_PER_HIDDEN_LAYER + 1)
        self.selected_number = \
                    IntVar(self, value = DEFAULT_NEURON_NUMBER_PER_HIDDEN_LAYER)
     
        self.option_menu = OptionMenu(self, self.selected_number, \
                                      *number_options)
        self.option_menu.grid(row=0, column=1)

        self.disable()
    
    def get(self):
        return self.selected_number.get()
        
    def enable(self):
        self.label.config(state = 'normal')
        self.option_menu.config(state = 'normal')
        
    def disable(self):
        self.label.config(state = 'disabled')
        self.option_menu.config(state = 'disabled')
class pgmsface(LabelFrame):

    def getPGMfileName(self):
        options = {'filetypes': [('pgm files', '.pgm')]}
        f = askopenfilename(**options)
        g = f.split('/')
        self.filenameVar.set(g[len(g) - 1])
        return f

    def __init__(self, x):
        LabelFrame.__init__(self, x)
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=10)         
        self.config(relief=GROOVE)
        self.config(borderwidth=2)
        self.config(text = "Testing")
        self.config(labelanchor = "n")

        self.loadPGMbutton = Button(self, text="Load PGM")
        self.loadPGMbutton.grid(row=0, column=0)
        
        self.filenameVar = StringVar()
        self.filenameVar.set("*****.pgm")
        
        self.fileNameLabel = Label(self, textvariable=self.filenameVar)
        self.fileNameLabel.config(relief=GROOVE, borderwidth=2, width=18)
        self.fileNameLabel.grid(row=0, column=1)

        self.pack()
class encoderface(LabelFrame):

    def __init__(self, x):
        LabelFrame.__init__(self, x)       
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=12)
        self.config(relief=GROOVE)
        self.config(borderwidth=2, padx=5, pady=5)
        self.config(text = "Encoder")
        self.config(labelanchor = "n")

        self.INSTRUCTION = StringVar()
        self.INSTRUCTION.set("Instruction")
        
        self.machinecode = StringVar()
        self.machinecode.set("")

        self.codeEntry = Entry(self, textvariable=self.INSTRUCTION)

        #self.codeEntry.configure(font=("Helvetica", 12), width=40)
        self.codeEntry.configure(width=40)

        self.codeButton = Button(self, text="Compile")

        self.VHPL = Label(self, text="VHPL")

        self.codeButton.grid(row=0, column=0, rowspan=4, sticky="wens")

        self.VHPL.grid(row=0, column=1, sticky="wens")
        self.VHPL.config(relief=GROOVE, borderwidth=2)
        
        self.codeEntry.grid(row=1, column=1, sticky="wens")
        self.codeEntry.config(fg="green", bg="black")
        
        self.pack()
    def draw_planet(self, planet):

        # global main_nav, main_canvas, label, planet_images, main_window

        new_x = self.convert_coordinates_x(planet.loc.x)
        new_y = self.convert_coordinates_y(planet.loc.y)
        name_y = self.convert_coordinates_name(planet.loc.y, planet.loc.size)
        color = self.get_terrain_color(planet.terrain)

        size = planet.loc.size, planet.loc.size
        planet_image = Image.open(self.get_terrain_image(planet.terrain))
        planet_image.thumbnail(size, Image.ANTIALIAS)
        planet_image_res = ImageTk.PhotoImage(planet_image)
        new_planet_image = planet_image_res
        self.planet_images.append(new_planet_image)
        label = Label(self.main_canvas)
        label.config(image=planet_image_res)
        label.config(background='black')
        label.grid()
        label.planet_image_res = planet_image_res  # keep a reference!
        label.place(anchor=CENTER, x=new_x, y=new_y)
        label.bind("<Button-1>", lambda event, arg=planet: self.controller.select_planet(event, arg))

        label_name = Label(self.main_canvas, text=planet.name, fg=self.app.conf.main_text_color, bg='black'
                           , borderwidth=1
                           , highlightthickness=0)
        label_name.place(anchor=CENTER, x=new_x, y=name_y)

        if self.app.conf.debug == 1:
            print "Drawing planet: [", planet.name, ",", new_x, ",", new_y, ",", planet.loc.size, ",", color, "]"
class SplitData:
    def __init__(self):
        root = Tk()
        root.title("split data")
        root.geometry("200x200")
        menu = Menu(root)
        root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Load data",command = self.load_data)
        self.notifcation = Label(root,text="")
        self.notifcation.grid(row=0,column=0)

        root.mainloop()
        
    def load_data(self):
        # calls the file dialog box
        name = askopenfilename() 
        (d_path,d_name)=split(name)
        fparts = d_name.split('.')
        count=0
        l_file = join(d_path,'run'+str(count)+fparts[0]+'.csv')
        out_f = open(l_file, 'w')
        with open(name) as in_f:
            for line in in_f:
                data = line.split(',')
                if len(data)>1:
                    out_f.write(line)
                else:
                    out_f.close()
                    count+=1
                    l_file = join(d_path,'run'+str(count)+fparts[0]+'.csv')
                    out_f = open(l_file, 'w')
        self.notifcation.config(text="Done")
 def set_label(self, name, text='', side=LEFT):
     if not self.labels.has_key(name):
         label = Label(self, relief=SUNKEN, anchor=W)
         label.pack(side=side)
         self.labels[name] = label
     else:
         label = self.labels[name]
     label.config(text=text)
Exemple #12
0
class UIScoreboard(object):
    """
        Display a scoreboard for the current game

    """


    def __init__(self, frame, h_size, v_size):
        # Define the size & position
        height, width, offset = 40, 100, 80
        x, y = h_size - width - offset, 0 + offset - height 

        # Make a dedicated frame 
        # This is usefull because label size is in text unit when
        #   it displays text (*gasp*)
        self._frame = Frame(frame, height = height, width = width) 
        # Avoid shrinking 
        self._frame.pack_propagate(0)
        self._frame.place(x = x, y = y)

        # Init the label
        self._label = Label(self._frame, text = "", justify = LEFT)
        # Pack it and make it fill the frame
        self._label.pack(fill = BOTH, expand = 1)

        self._score_02 = None
        self._score_13 = None

    
    @property
    def score_02(self):
        return self._score_02


    @property
    def score_13(self):
        return self._score_13


    @score_02.setter
    def score_02(self, value):
        self._score_02 = value
        self._update_score_text()


    @score_13.setter
    def score_13(self, value):
        self._score_13 = value
        self._update_score_text()


    def _update_score_text(self):
        name_02 = "Team 0_2"
        name_13 = "Team 1_3"
        text_02 = str(self._score_02)
        text_13 = str(self._score_13)
        self._label.config(text = name_02 + ": " + text_02 + "\n" + \
                                  name_13 + ": " + text_13)
class UsernameOverlay(Overlay):
    def __init__(self, *args, **kwargs):
        Overlay.__init__(self, *args, **kwargs)
        self.label = ""
        self.field = ""
        self.button = ""
        self.user = ""
        self.logger = JPYLogger(self)
        self.config(
            background="gold",
            cursor="arrow"
        )

        self.renderLabel()
        self.renderField()
        self.renderButton()

    def renderLabel(self):
        self.label = Label(self)
        self.label.config(
            text="CHANGE PLAYERNAME",
            font=Fonts.MONEY_BIG,
            background="gold"
        )
        self.label.pack()

    def renderField(self):
        self.field = Entry(self)
        self.field.config(
            relief="solid",
            bd=2,
            highlightcolor="black",
            font=Fonts.USER_LABEL_NAME_BIG
        )
        self.field.pack()

    def renderButton(self):
        Label(self, text='\n', background="gold").pack()
        self.button = Button(self)
        self.button.config(
            text="OK",
            relief="solid",
            background="black",
            foreground="gold",
            font=Fonts.MONEY_MEDIUM,
            command=self.save
        )
        self.button.pack()

    def save(self):
        self.logger.prompt("User " + str(self.user.id) + " changed name from '" + self.user.name.get() + "' to '" + self.field.get() + "'")
        self.user.name.set(self.field.get())
        self.hide(self)
        self.root.root.inputController.blockBuzzer = False

    def insert(self, user):
        self.field.delete(0, END)
        self.field.insert(0, user.name.get())
Exemple #14
0
class LoginWindow(Frame):

	def __init__(self,parent,graphics):
		Frame.__init__(self)
		self.grid()
		self.parent = parent
		self.graphics = graphics		
		self.configure(bg=self.graphics.mainColor)
		Style().configure('green/black.TButton', background='black', foreground='black')
		Style().configure("Red.TLabel", foreground="red")
		
		
		self.grid_columnconfigure (1, weight=1)
		self.grid_rowconfigure 	  (0, weight=1)
		self.grid_rowconfigure    (9, weight=1)

		# Enter Username
		self.usernameLabel = Label(self, text="Username", bg = self.graphics.mainColor)#, bg=self.color,padx=5)
		#usernameLabel = Label(self, text="username", bg=self.color,padx=5)
		self.usernameLabel.grid(row=3,column=1,sticky='s')
		self.usernameField = Entry(self, width=40)#bd =0, width=40)
		#usernameField = Entry(self, width=40,bd =1)
		self.usernameField.insert(END, '')
		self.usernameField.grid(row=4,column=1,sticky='n')
		self.usernameField.bind("<Return>",(lambda event: self.login(self.usernameField, self.passwordField)))
		self.usernameField.focus()

		# Enter Password
		self.passwordLabel = Label(self, text="Password", bg = self.graphics.mainColor)#, bg=self.color,padx=5)
		#passwordLabel = Label(self, text="password", bg=self.color,padx=5)
		self.passwordLabel.grid(row=5,column=1,sticky='s')
		self.passwordField = Entry(self, show="*", width=40)#bd =0, width=40)
		#passwordField = Entry(self, show="*", width=40,bd =1)
		self.passwordField.grid(row=6,column=1,sticky='n')
		self.passwordField.bind("<Return>",(lambda event: self.login(self.usernameField,self.passwordField)))

		#output
		self.outputLabel = Label(self, text="", fg='red', bg = self.graphics.mainColor)#,bg=self.color,padx=5)
		self.outputLabel.grid(row=7,column=1, pady=5, sticky='s')

		# Attempt to login
		self.loginButton = Button(self, text="Enter", width=15, command=lambda: self.login(self.usernameField, self.passwordField))
		#loginButton = Button(self, text="Enter", width=15, command=lambda: self.login(usernameField, passwordField))
		self.loginButton.grid(row=8,column=1,pady=5)

	def login(self,username,password,event=None):		

		if self.graphics.POS.login(username.get(),password.get()) == True:
			print "logged in!"
			self.graphics.liftLayer("main")
			self.usernameField.delete(0, 'end')
			self.passwordField.delete(0, 'end')
			self.outputLabel.config(text="")
		else:
			if self.graphics.POS.login(username.get(),password.get()) != None:
				self.outputLabel.config(text="Incorrect Login")
Exemple #15
0
 def set_label(self, name, text='', side=LEFT, width=0):
     if name not in self.labels:
         label = Label(self, borderwidth=0, anchor=W)
         label.pack(side=side, pady=0, padx=4)
         self.labels[name] = label
     else:
         label = self.labels[name]
     if width != 0:
         label.config(width=width)
     label.config(text=text)
Exemple #16
0
class StatusBar(Frame, OutputPipe):
    """
    A basic definition for a statusBar style widget that can be updated
    during runtime
    This class has been derived from the link at the header of this file
    """

    def __init__(self, parent, text_link=None):
        """
        Construct the status bar instance

        :parent:        The parent tk widget that the taskbar should sit in
        :text_link:     Allows the user to supply there own undoable text value
        """
        Frame.__init__(self, parent)
        if text_link is None:
            text_link = StringVar(value="Running")
        self._text = text_link
        self._label = Label(self, bd=1, relief=SUNKEN, anchor=W, textvariable=self._text)
        self._label.pack(fill=X)

    def set_text_f(self, format, *args):
        """
        Set the text of the status bar with formatting

        :format: The formatting string to use
        """
        self._text.set(format % args)
        self.change_bg("green")
        self._label.update_idletasks()

    def set_text(self, text):
        """
        Set the text of the status bar
        """
        self.set_text_f("%s", text)

    def alert(self, msg, level):
        """
        Posts text to the status bar, and colours the background based on an alert level
        """
        self.set_text(msg)
        if level is Debug.Level.INFO:
            self.change_bg("green")
        elif level is Debug.Level.ERROR:
            self.change_bg("yellow")
        else:
            self.change_bg("red")


    def clear(self):
        self.set_text("%s", "")

    def change_bg(self, colour):
        self._label.config(bg=colour)
 def __init__(self, *args, **kwargs):
     GameState.__init__(self, *args, **kwargs)
     image = PhotoImage(file="resources/opener.gif")
     opener = Label(self)
     self.config(background="gold")
     opener.config(
         image=image,
         background="blue"
     )
     opener.image = image
     opener.place(x=0, y=0,relwidth=1, relheight=1)
Exemple #18
0
class ViewMediaFrame(BasePAFrame):
    """
    фрейм с картинкой
    """

    def __init__(self, *args, **kwargs):
        BasePAFrame.__init__(self, *args, **kwargs)

        self.vlc_instance = vlc.Instance()
        self.vlc_player = self.vlc_instance.media_player_new()

        self.platform = platform.system().lower()

        self.media_label = Label(self)

    def _pa_layout(self):
        self.media_label.pack()

    def set_image(self, image, width, height):
        if not image:
            self.reset()
            return

        image_width, image_height = image.size
        if image_height > height:
            percent = height/float(image_height)
            width = int(image_width * percent)
        elif image_width > width:
            percent = width / float(image_width)
            height = int(image_height * percent)
        photo_image = ImageTk.PhotoImage(
            image.resize((width, height), Image.ANTIALIAS))
        self.media_label.config(image=photo_image)
        self.media_label.image = photo_image

    def set_video(self, video_path):
        """
        проигрывает указанное видео
        """
        self.vlc_player.set_media(
            self.vlc_instance.media_new(video_path))
        if self.platform == 'windows':
            self.vlc_player.set_hwnd(self.media_label.winfo_id())
        else:
            self.vlc_player.set_xwindow(self.media_label.winfo_id())
        # self.vlc_player.play()

    def reset(self):
        self.media_label.config(image=None)
        self.media_label.image = None
Exemple #19
0
class tkimg(Frame):
    img=None
    def showImg(self, fn):
        im = Image.open(fn)
        tag, (x0, y0, x1, y1), offset, extra = im.tile[0]
        im.size = x1-x0, y1-y0
        #image = im.resize((int(im.size[0]*(self.zoom/100.)), int(im.size[1]*(self.zoom/100.))),Image.ANTIALIAS)
        self.imgholder=ImageTk.PhotoImage(im)
        if self.img==None:
            self.img=Label(self,image=self.imgholder)
            self.img.grid(row=1,column=1,sticky="nwes")
        else:
           self.img.config(image=self.imgholder)

    def clear(self):
        if self.img:
            self.img.config(image="")
Exemple #20
0
class TkStub:
    def __init__(self):
        root = Tk()
        root.title("tk_stub")
        root.geometry("400x200")
        menu = Menu(root)
        root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Load data",command = self.do_this)
        self.notifcation = Label(root,text="")
        self.notifcation.grid(row=0,column=0)

        root.mainloop()
        
    def do_this(self):
        name = askopenfilename() 
        (d_path,d_name)=split(name)
        self.notifcation.config(text=join(d_path,d_name))
Exemple #21
0
class TimeDisp(object):
    '''Project time summary and list of dates and times.'''
    def __init__(self, master, project, genq):
        self.frame = Frame(master, borderwidth=2)
        self.project = project
        self.genq = genq
        Button(self.frame, text=project, command=self._pop).pack(side=TOP)
        self.time = 0 #total time on project over period.
        self.label = Label(self.frame)
        self.label.pack(side=TOP)
        self.disp = Text(self.frame, height=8, width=20, wrap=WORD,
                         bg='sea green', spacing1=5)
        self.disp.pack(side=BOTTOM)

    def append(self, date, time_):
        """Insert new date and time at the end."""
        self.time = self.time + time_
        hour = int(time_/3600.)
        minute = int((time_ - (hour*3600))/60.)
        sec = time_ - ((hour * 3600) + (minute * 60))
        time_str = (str(date) + ': ' + str(hour) + ':' + str(minute) +
                    ':' + str(sec) + '\n')
        self.disp.insert(END, time_str)

    def update(self):
        """Take the time and put it into readable format."""
        hour = int(self.time/3600.)
        minute = int((self.time - (hour*3600))/60.)
        sec = self.time - ((hour * 3600) + (minute * 60))
        time_str = str(hour) + ":" + str(minute) + ":" + str(sec)
        self.label.config(text="Total: "+time_str)
        self.frame.pack(side=LEFT)

    def clear(self):
        """Clear the text display and forgets the pack"""
        self.disp.delete('1.0', END)
        self.time = 0
        self.frame.pack_forget()

    def _pop(self, event=None):
        """Pops the project name into the project"""
        self.genq.insert("Project", self.project)
Exemple #22
0
    def draw_planet_highlighted(self, planet):

        # global main_nav, main_canvas, label, planet_images, main_window

        new_x = self.convert_coordinates_x(planet.loc.x)
        new_y = self.convert_coordinates_y(planet.loc.y)
        name_y = self.convert_coordinates_name(planet.loc.y, planet.loc.size)
        color = self.get_terrain_color(planet.terrain)

        size = planet.loc.size, planet.loc.size
        planet_image = Image.open(self.get_terrain_image(planet.terrain))
        planet_image.thumbnail(size, Image.ANTIALIAS)
        planet_image_res = ImageTk.PhotoImage(planet_image)
        new_planet_image = planet_image_res
        self.planet_images.append(new_planet_image)
        label_planet = Label(self.main_canvas)
        label_planet.config(image=planet_image_res)
        label_planet.config(background='black')
        label_planet.planet_image_res = planet_image_res  # keep a reference!
        label_planet.place(anchor=CENTER, x=new_x, y=new_y)
        label_planet.bind("<Button-1>", lambda event, arg=planet: self.controller.select_planet(event, arg))
        label_name = Label(self.main_canvas, text=planet.name, fg='red', bg='black', borderwidth=1
                           , highlightthickness=0)
        label_name.place(anchor=CENTER, x=new_x, y=name_y)

        if self.app.conf.debug == 1:
            print "Drawing planet: [", planet.name, ",", new_x, ",", new_y, ",", planet.loc.size, ",", color, "]"

        # get nearest planet and draw a line
        if self.has_selected:
            nearest_planet = self.get_nearest_planet(planet)
            l = self.get_line_points((planet.loc.x, planet.loc.y)
                                     , (nearest_planet.loc.x, nearest_planet.loc.y)
                                     , planet.loc.size
                                     , nearest_planet.loc.size)
            self.main_canvas.create_line(l.x1, l.y1, l.x2, l.y2, fill='blue', dash=(4, 4))
            self.main_canvas.pack()
            self.app.debug(("Drawing line:", l.x1, ',', l.y1, ',', l.x2, ',', l.y2))
        else:
            self.app.debug("Line next time")
            self.has_selected = True
class Tooltip_Helper:
  """
  Class to help show tooltips on Tkinter Canvases.
  """
  def __init__(self, canvas):
    """
    |canvas|: the canvas on which tooltips will be shown.
    """
    self._canvas = canvas
    self._tip = None
  def show_tooltip(self, x, y, text, background=TOOLTIP_BACKGROUND):
    """
    Shows a tooltip containing the given |text| close to the point (|x|, |y|) on
        the canvas.
    """
    x += self._canvas.winfo_rootx() + 10
    y += self._canvas.winfo_rooty() + 10
    geometry = '+%d+%d' % (x, y)
    if not self._tip:
      self._tip = Toplevel(self._canvas)
      self._tip.wm_overrideredirect(1)
      self._tip.wm_geometry(geometry)
      try:
        # for Mac OS
        self._tip.tk.call('::tk::unsupported::MacWindowStyle', 'style',
            self._tip._w, 'help', 'noActivates')
      except TclError:
        pass
      self.label = Label(self._tip, text=text, justify=LEFT,
          background=background, relief=SOLID, borderwidth=1, font=DEFAULT_FONT)
      self.label.pack()
    else:
      self._tip.geometry(geometry)
      self.label.config(text=text, background=background)
  def hide_tooltip(self):
    """
    Hides the previously added tooltip, if any.
    """
    if self._tip:
      self._tip.destroy()
      self._tip = None
class DowntextFrame(Frame):
    def __init__(self, master=None, cnf={}, **kw):
        Frame.__init__(self, master=master, cnf=cnf, **kw)
        self.master = master
        self.countdownText = ''
        self.countdown_label = Label(master = self, text = 'initializing...', font = FONT_DOWNTEXT_FONT, fg = 'black')
        self.borderLabel = Label(master = self, text = '   ', font = FONT_DOWNTEXT_FONT, fg = 'black')
        self.anotherLabel = Label(master = self, text = '', font = FONT_DOWNTEXT_FONT, fg = 'black')


    def grid(self, cnf={}, **kw):
        Frame.grid(self, cnf=cnf, **kw)
        self.countdown_label.grid(row = 0, column = 0)
        self.borderLabel.grid(row = 0, column = 1)
        self.anotherLabel.grid(row = 0, column = 2)


    def update_countdown(self, text):
        self.countdownText = text
        self.countdown_label.config(text = str(text))
        # todo continue
Exemple #25
0
    def display(self, frame_obj):

        canvas_popup = Canvas(frame_obj, background=conf.left_nav_background)
        # canvas_popup.config(x=0, y=0)
        canvas_popup.place(x=(frame_obj.sw/2), y=(frame_obj.sh/2)-100)

        if self.title != "":
            title_label = Label(canvas_popup, text=self.title, fg=conf.main_text_color)
            title_label.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background)
            title_label.grid(row=0, sticky='e,w', padx=10, pady=10)

        if self.content != "":
            content_label = Label(canvas_popup, text=self.content, fg=conf.main_text_color)
            content_label.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background)
            content_label.grid(row=1, sticky='e,w', padx=10, pady=10)

        if self.content != "":
            action_button = Button(canvas_popup, text="Ok", fg=conf.main_text_color)
            action_button.config(highlightbackground=conf.left_nav_background, background=conf.left_nav_background)
            action_button.bind("<Button-1>", self.dismiss)
            action_button.grid(row=2, sticky='e,w', padx=10, pady=10)
class clockface(LabelFrame):
    
    def __init__(self, x):
        LabelFrame.__init__(self, x)
#        self.default_font = tkFont.nametofont("TkDefaultFont")
#        self.default_font.configure(family="Helvetica",size=10)

        self.config(relief=GROOVE)
        self.config(borderwidth=2)
        self.config(text = "Up Time")
        self.config(labelanchor = "n")
        
        self.Hsv = StringVar()
        self.Hsv.set("")
        self.Hlabel = Label(self, textvariable = self.Hsv)
        self.Hlabel.grid(row=0, column=0, sticky="wens")
        self.Hlabel.config(font=("Courier", 14))
        
        self.Msv = StringVar()
        self.Msv.set("")
        self.Mlabel = Label(self, textvariable = self.Msv)
        self.Mlabel.grid(row=1, column=0, sticky="wens")
        self.Mlabel.config(font=("Courier", 14))
        
        self.Ssv = StringVar()
        self.Ssv.set("")
        self.Slabel = Label(self, textvariable = self.Ssv)
        self.Slabel.grid(row=2, column=0, sticky="wens")
        self.Slabel.config(font=("Courier", 14))

        self.pack()
Exemple #27
0
def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('-W', '--width',  type='int', default=300)
    parser.add_option('-H', '--height', type='int', default=300)
    parser.add_option('-c', '--center', type='complex', default=0+0j)
    parser.add_option('-s', '--side',   type='float', default=4)
    (options, args) = parser.parse_args()

    root = Tk()
    l = Label(root)
    l.pack()

    W, H = options.width, options.height
    center, side = options.center, options.side

    im = Image.new('P', (W, H), 0)
    im.putpalette([randrange(256) for n in range(3 * 256)])
    p = im.load()
    
    z = z_converter(W, H, center, side)
    l.pim = PhotoImage(im)
    l.config(image=l.pim)

    def paint_column(x):
        if x % 10 == 0: print "Column %d" % x
        for y in range(H):
            p[x, y] = pixel(z(x, y))
        l.pim = PhotoImage(im)
        l.config(image=l.pim)

        if x + 1 < W:
            root.after(1, paint_column, x + 1)

    def start(event):
        root.after(1, paint_column, 0)

    root.bind('<FocusIn>', start)
    root.mainloop()
class QuestionOverlay(Overlay):
    def __init__(self, *args, **kwargs):
        Overlay.__init__(self, *args, **kwargs)
        self.label = ""
        self.config(background="blue")

        self.drawLabel()

    def drawLabel(self):
        self.label = Label(self)
        self.label.config(
            textvar=self.text,
            font=Fonts.SYSTEM_BIG,
            background=self["background"],
            foreground="white",
            wraplength=Constants.SCREENW * 0.8
        )
        self.label.place(relwidth=1, relheight=1)

    def hide(self, event):
        Overlay.hide(self, event)
        self.root.root.questionManager.candidate = None
class TkValidEntry(BaseTkValidEntry):    
    
    def __init__(self,master,name,width,default,var):
        
        BaseTkValidEntry.__init__(self,master,name,width,default,var)
        
        self.label = Tklabel(self,text=name,width=width,anchor=W,justify=LEFT)
        
        self.label.grid(row=0,column=0,sticky=NSEW)
        
        self.statuslabel = Tklabel(self,text='',width=1,anchor=W,background='lightblue',justify=LEFT)
        
        self.statuslabel.grid(row=0,column=2,sticky=NSEW)
        
        self.ruleslabel = Tklabel(self,text=self.var.name(),width=16,anchor=W,justify=LEFT)

        self.ruleslabel.grid(row=0,column=3,sticky=NSEW)

        self.grid_rowconfigure(0, weight=1, uniform="foo")
        
    def validate(self):
        
        print "validate"
        if self.var(self.sv.get()) == True:
            self.statuslabel.config(background='lime')
            return
            
        self.statuslabel.config(background='pink')
        
    def focus_next_widget(self,event):
        nextwidget = event.widget.tk_focusNext()
        nextwidget.focus()        
        nextwidget.selection_range(0,END)
        return("break")
    
    def select_all(self,event):       
        event.widget.selection_range(0,END)
        return("break")
Exemple #30
0
    def mkMemory(self, f):
        self.MEMORYframe = Frame(f)
        self.MEMORYframe.config(relief=GROOVE)
        self.MEMORYframe.config(borderwidth=2)

        E = Frame(self.MEMORYframe)

        self.CLEAR = self.mkButton(E, "ClearMem", 0, 0)
        self.RANDOM = self.mkButton(E, "RandomMem", 0, 1)
        self.READ = self.mkButton(E, "ReadMem", 1, 0)
        self.WRITE = self.mkButton(E, "WriteMem", 1, 1)
        self.BUSTOMEM = self.mkButton(E, "BusToMem", 2, 0, 1, 2)

        F = Frame(self.MEMORYframe)
        
        for i in Range8:
            L = Label(F, textvariable=self.MEMORY[i])
            L.config(relief=GROOVE, borderwidth=2, bg="black", fg="yellow", height=1)
            L.grid(row=0, column=i, sticky="wens", ipadx=5)

        E.pack(side=TOP)
        F.pack(side=BOTTOM)

        self.MEMORYframe.grid(row=18, column=9, rowspan=5, columnspan=2, sticky="wens")
Exemple #31
0
class GeoGame(Frame):
    def __init__(self, master):
        self.master = master
        self.master.title("GeoGame")
        self.master.protocol('WM_DELETE_WINDOW', self.close)

        self.smallim = Image.open("textures/maps/medium_map.jpg")
        self.bigim = Image.open("textures/maps/big_map.jpg")
        self.bigim.load()
        self.customFont = tkFont.Font(family="Comic Sans MS", size=12)
        self.im2 = ImageTk.PhotoImage(self.smallim)

        self.click = []

        self.topFrame = Frame(master)
        self.topFrame.pack(side=TOP)
        self.bottomFrame = Frame(master)
        self.bottomFrame.pack(side=BOTTOM, fill="both")
        self.canvas = Canvas(self.topFrame, width=1200, height=600)
        self.canvas.pack(expand="yes", fill="both")
        self.label = self.canvas.create_image(0,
                                              0,
                                              image=self.im2,
                                              anchor='nw')
        click = self.canvas.bind("<Button-1>", self.callback)

        self.crosshairs = Image.open(
            "textures/crosshairs/targetcrosshair.gif"
        )  #GIFs ONLY, PNG's transparency doesn't work
        self.crosshairs2 = Image.open("textures/crosshairs/clickcrosshair.gif")
        self.cross_width, self.cross_height = self.crosshairs.size
        self.cross_width2, self.cross_height2 = self.crosshairs2.size
        self.cross = ImageTk.PhotoImage(self.crosshairs)
        self.cross2 = ImageTk.PhotoImage(self.crosshairs2)
        self.first_round = 0
        self.zoomed = False

        self.d = database.Database()
        self.tot_score = 0
        self.level = 1
        self.level_pass = self.max_score()
        self.difficulty = 50
        self.go_number = 1
        self.level_score = 0
        self.asked_index = [(len(self.d.data) + 1)]

        self.text = Text(self.bottomFrame,
                         height=1,
                         width=40,
                         font=self.customFont)
        self.text.pack(side=LEFT)
        self.scoreText = Text(self.bottomFrame, height=1, width=10)
        self.scoreText.pack(side=RIGHT)
        self.scoreText.insert(END, str(self.tot_score))
        self.scoreText.config(state=DISABLED)
        self.scoreLabel = Label(self.bottomFrame, text="Total Score")
        self.scoreLabel.pack(side=RIGHT)
        self.text.insert(END, "Your next city is: ")
        self.text.config(state=DISABLED)
        self.levelText = Text(self.bottomFrame, height=1, width=10)
        self.levelText.pack(side=RIGHT)
        self.levelText.insert(
            END,
            str(self.level_score) + "/" + str(int(self.max_score())))
        self.levelText.config(state=DISABLED)
        self.levelLabel = Label(self.bottomFrame, text='Level 1 Score')
        self.levelLabel.pack(side=RIGHT)

        self.gamesetup()

    def close(self):
        self.master.destroy()
        self.d.close()

    def zoom_in(self):
        self.canvas.delete(self.label)
        self.zoomposition_x = self.click[0] - 60
        self.zoomposition_y = self.click[1] - 30
        self.upper = (self.click[1] * 10) - 300
        self.left = (self.click[0] * 10) - 600
        right = (self.click[0] * 10) + 600
        lower = (self.click[1] * 10) + 300
        self.crop_big = self.bigim.crop((self.left, self.upper, right, lower))
        self.crop_big2 = ImageTk.PhotoImage(self.crop_big)
        self.zoom = self.canvas.create_image(0,
                                             0,
                                             image=self.crop_big2,
                                             anchor='nw')
        self.zoomed = True

    def zoom_out(self):
        self.canvas.delete(self.zoom)
        self.label = self.canvas.create_image(0,
                                              0,
                                              image=self.im2,
                                              anchor='nw')
        self.zoomed = False

    def callback(self, event):
        self.click = [event.x, event.y]
        if self.zoomed == False:
            self.zoom_in()
        else:
            x = int(int(self.city.xcord)) - self.left
            y = int(int(self.city.ycord)) - self.upper

            self.target3 = self.canvas.create_image(x - self.cross_width / 2,
                                                    y - self.cross_height / 2,
                                                    image=self.cross,
                                                    anchor='nw')
            self.target4 = self.canvas.create_image(
                self.click[0] - self.cross_width2 / 2,
                self.click[1] - self.cross_height2 / 2,
                image=self.cross2,
                anchor='nw')
            self.master.update()
            time.sleep(2)
            self.canvas.delete(self.target3)
            self.gameplay()

    def gamesetup(self):
        self.city, self.asked_index = self.d.choose_city(
            self.asked_index, self.difficulty)
        self.text.config(state="normal")
        self.text.delete("1.19", END)
        self.text.insert(END, self.city.cityname + ", " + self.city.country)
        self.text.config(state=DISABLED)
        self.score = 0

    def gameplay(self):
        if self.first_round != 0:
            self.canvas.delete(self.target)
        go_score = self.distance_score()
        self.tot_score += go_score
        self.level_score += go_score

        self.scoreText.config(state="normal")
        self.scoreText.delete("1.00", END)
        self.scoreText.insert(END, str(self.tot_score))
        self.scoreText.config(state=DISABLED)
        self.levelText.config(state="normal")
        self.levelText.delete("1.00", END)
        self.levelText.insert(
            END,
            str(self.level_score) + "/" + str(int(self.max_score())))
        self.levelText.config(state=DISABLED)

        self.zoom_out()

        x = int(int(self.city.xcord) / 10)
        y = int(int(self.city.ycord) / 10)
        self.x_click = self.zoomposition_x + int(self.click[0] / 10)
        self.y_click = self.zoomposition_y + int(self.click[1] / 10)

        self.target = self.canvas.create_image(int(x) - self.cross_width / 2,
                                               int(y) - self.cross_height / 2,
                                               image=self.cross,
                                               anchor='nw')

        self.target2 = self.canvas.create_image(
            int(self.x_click) - self.cross_width2 / 2,
            int(self.y_click) - self.cross_height2 / 2,
            image=self.cross2,
            anchor='nw')

        self.canvas.tag_raise(self.target2)
        self.first_round = 1
        self.city.update_difficulty(self.dist)
        self.go_number += 1

        if self.go_number == 10:
            if self.level_score > self.level_pass:
                self.level_up()
            else:
                self.level_fail()
        self.gamesetup()

    def distance_score(self):
        self.offset_x = float(self.click[0] + self.left)
        self.offset_y = float(self.click[1] + self.upper)

        click_long = (self.offset_x - 6000) * 0.03
        click_lat = (3000 - self.offset_y) * 0.03

        city_long = (int(self.city.xcord) - 6000) * 0.03
        city_lat = (3000 - int(self.city.ycord)) * 0.03

        self.dist = self.global_distance(click_long, click_lat, city_long,
                                         city_lat)

        if self.dist == 0:
            score = self.max_score()
        else:
            score = int(self.max_score() / (self.dist**0.5))

        if score < 0:
            score = 0
        print "You scored: " + str(score)
        return score

    def global_distance(self, lon1, lat1, lon2, lat2):
        """
        Calculate the great circle distance between two points 
        on the earth (specified in decimal degrees)
        """
        # convert decimal degrees to radians
        lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

        # haversine formula
        dlon = lon2 - lon1
        dlat = lat2 - lat1
        a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
        c = 2 * asin(sqrt(a))
        r = 6371  # Radius of earth in kilometers. Use 3956 for miles
        return c * r

    def level_up(self):
        self.level += 1
        self.levelLabel.config(text="Level " + str(self.level) + " Score")
        self.level_pass = self.max_score()
        print "LEVEL UP, Begin Level " + str(self.level)
        self.difficulty += 50
        self.go_number = 1
        self.level_score = 0
        self.levelText.config(state="normal")
        self.levelText.delete("1.00", END)
        self.levelText.insert(
            END,
            str(self.level_score) + "/" + str(int(self.max_score())))
        self.levelText.config(state=DISABLED)

    def level_fail(self):
        self.level = 1
        self.levelLabel.config(text="Level " + str(self.level) + " Score")
        self.level_pass = self.max_score()
        print "YOU FAILED, Begin Level 1"
        self.difficulty = 50
        self.go_number = 1
        self.level_score = 0
        self.tot_score = 0
        self.scoreText.config(state="normal")
        self.scoreText.delete("1.00", END)
        self.scoreText.insert(END, str(self.tot_score))
        self.scoreText.config(state=DISABLED)
        self.levelText.config(state="normal")
        self.levelText.delete("1.00", END)
        self.levelText.insert(
            END,
            str(self.level_score) + "/" + str(int(self.max_score())))
        self.levelText.config(state=DISABLED)

    def max_score(self):

        return int(1000 * (1.2**(self.level - 1)))
Exemple #32
0
class Aligner:
    def __init__(self, master, region_folder, bounding_dimension=700):
        # Initialise data
        self.region_folder = os.path.abspath(region_folder)
        self.bounding_dimension = bounding_dimension
        self.clb_file = os.path.join(self.region_folder, \
                                     os.path.split(self.region_folder)[1]+".clb")
        self.images, self.size = self.read_images(self.region_folder)

        self.offset = {}
        self.global_x_offset = 0
        self.global_y_offset = 0

        middle = (int(self.size[0]/2.0), int(self.size[1]/2.0))
        square_half_side = int(0.025*max(self.size))
        self.square = [middle[0]-square_half_side, middle[1]-square_half_side, \
                       middle[0]+square_half_side, middle[1]+square_half_side]

        self.img_index = []
        for img in self.images.keys():
            time = os.path.basename(img).split("_")
            for t in time:
                if t.endswith(".jpg"):
                    time = t.strip(".jpg")
                    break
            self.img_index.append((int(time), img))
        self.img_index.sort()

        self.check_calibration()
        ########################################################################

        # Initialise GUI
        # Set window title
        self.master = master
        master.title("Aligner")

        # Set window size
        master.geometry("%dx%d+00+00" % (self.bounding_dimension, self.bounding_dimension))

        # self.label = Label(master, text="Welcome to Aligner!")
        # self.label.pack()

        self.label_index = 0
        self.set_photo()
        self.label = Label(master, image=self.photo)
        self.label.focus_set()
        self.label.bind("<Return>", self.cycle_images)
        self.label.bind("<Left>", self.left_key)
        self.label.bind("<Right>", self.right_key)
        self.label.bind("<Up>", self.up_key)
        self.label.bind("<Down>", self.down_key)
        self.label.bind("<q>", self.quit)
        self.label.pack()

    def set_photo(self):
        # Sort out the image
        tn = self.images[self.img_index[self.label_index][1]].copy()
        # Offset the image
        tn = offset(tn, self.global_x_offset, self.global_y_offset)
        draw = ImageDraw.Draw(tn, 'RGBA')
        draw.rectangle(self.square, (255, 0, 0, 125))
        del draw
        tn.thumbnail((self.bounding_dimension, self.bounding_dimension), Image.ANTIALIAS)
        self.photo = ImageTk.PhotoImage(tn)

    def cycle_images(self, event):
        self.offset[str(self.img_index[self.label_index][0])] = (self.global_x_offset, self.global_y_offset)
        self.save_calibration()
        self.label_index += 1
        if self.label_index >= len(self.img_index):
            self.master.quit()
        else:
            self.rebuild_image()

    def quit(self, event):
        self.master.quit()

    def left_key(self, event):
        self.global_x_offset -= 1
        self.rebuild_image()

    def right_key(self, event):
        self.global_x_offset += 1
        self.rebuild_image()

    def up_key(self, event):
        self.global_y_offset -= 1
        self.rebuild_image()

    def down_key(self, event):
        self.global_y_offset += 1
        self.rebuild_image()

    def rebuild_image(self):
        self.set_photo()
        self.label.config(image=self.photo)

    def read_images(self, img_folder):
        """Read in all images captured for given OSM file."""
        imgs = []
        for o in os.listdir(img_folder):
            d = os.path.join(img_folder, o)
            if os.path.isfile(d) and o.lower().endswith(".jpg"):
                imgs.append(d)

        images = {}
        for i in imgs:
            images[i] = Image.open(i)
        image_size = (images.values()[0].size)
        return images, image_size

    def save_calibration(self):
        with open(self.clb_file, "w") as calibration_file:
            json.dump(self.offset, calibration_file, sort_keys=True, indent=2, separators=(',', ': '))

    def check_calibration(self):
        if os.path.isfile(self.clb_file):
            print "Calibration file already exists:\n    %s" % self.clb_file
            with open(self.clb_file, "r") as calibration_file:
                self.offset = json.load(calibration_file)
                calib = [int(i) for i in self.offset.keys()]
            if len(self.img_index) != len(calib):
                rm = []
                print "Not all images are aligned."
                print "Aligning only the images with missing alignment values:"
                for i, j in self.img_index:
                    if i in calib:
                        rm.append((i,j))
                    else:
                        print ">    %s" % j
                for i in rm:
                    self.img_index.remove(i)
            else:
                print "All images are aligned."
                print "If you want to align all the images again please remove the *.clb file."
                print "If you want to align some of the images again please remove specific entry in the *.clb file."
                sys.exit()
Exemple #33
0
class view(Tk):
    def mkStringVar(self, s):
        R = StringVar()
        R.set(s)
        return R

    def mkLabel(self, f, T, r, c, rs=1, cs=1):
        if isinstance(T, type(StringVar())):
            R = Label(f, textvariable=T, relief=GROOVE, borderwidth=2)
        else:
            R = Label(f, text=T, relief=GROOVE, borderwidth=2)
        R.grid(row=r, column=c, rowspan=rs, columnspan=cs, sticky="wens")
        return R

    def mkLabelList(self, f, SV, r):
        R = []
        for i in range(len(SV)):
            R.append(self.mkLabel(f, SV[i], r, i + 1))
        return R

    def mkButton(self, f, t, r, c, rs=1, cs=1):
        R = Button(f, text=t)
        R.grid(row=r, column=c, rowspan=rs, columnspan=cs, sticky="wens")
        return R

# ===== HALT et cetera =========================================================

    def mkHaltArea(self, f):
        self.HALTframe = Frame(f)
        self.HALTframe.config(relief=GROOVE)
        self.HALTframe.config(borderwidth=2)

        self.HALTbutton = Button(self.HALTframe, text="HALT", width=10)
        self.READMEbutton = Button(self.HALTframe, text="README", width=10)

        self.HALTbutton.config(borderwidth=2, relief=GROOVE, fg="red")
        self.HALTbutton.config(command=self.quit)
        self.READMEbutton.config(borderwidth=2, relief=GROOVE, fg="red")

        self.HALTbutton.pack(side=LEFT, fill=BOTH)
        self.READMEbutton.pack(side=RIGHT, fill=BOTH)

        self.HALTframe.grid(row=0,
                            column=9,
                            rowspan=1,
                            columnspan=4,
                            sticky="wens")

# ==============================================================================

    def mkProgramControl(self, f):
        self.PROGRAMCONTROLframe = Frame(f)
        self.PROGRAMCONTROLframe.config(relief=GROOVE)
        self.PROGRAMCONTROLframe.config(borderwidth=2)

        self.runButton = Button(self.PROGRAMCONTROLframe, text="RUN", width=10)
        self.runButton.grid(row=0, column=0, sticky="wens", padx=29, pady=7)

        self.stepButton = Button(self.PROGRAMCONTROLframe,
                                 text="STEP",
                                 width=10)
        self.stepButton.grid(row=1, column=0, sticky="wens", padx=29, pady=5)

        self.noStepButton = Button(self.PROGRAMCONTROLframe,
                                   text="NOSTEP",
                                   width=10)
        self.noStepButton.grid(row=2, column=0, sticky="wens", padx=29, pady=7)

        self.PROGRAMCONTROLframe.grid(row=17,
                                      column=11,
                                      rowspan=6,
                                      columnspan=2,
                                      sticky="wens")

# ==============================================================================

    def getPGMfileName(self):
        options = {'filetypes': [('pgm files', '.pgm')]}
        f = askopenfilename(**options)
        g = f.split('/')
        self.filenameVar.set(g[len(g) - 1])
        return f

    def mkProgramLoad(self, f):
        self.PROGRAMLOADframe = Frame(f)
        self.PROGRAMLOADframe.config(relief=GROOVE)
        self.PROGRAMLOADframe.config(borderwidth=2)

        self.loadPGMbutton = Button(self.PROGRAMLOADframe, text="Load PGM")
        self.loadPGMbutton.config(width=14)
        self.loadPGMbutton.pack(side=LEFT, fill=BOTH, padx=20, pady=5)

        self.filenameVar = StringVar()
        self.filenameVar.set("*****.pgm")

        self.fileNameLabel = Label(self.PROGRAMLOADframe,
                                   textvariable=self.filenameVar)
        self.fileNameLabel.config(relief=GROOVE, borderwidth=2, width=17)
        self.fileNameLabel.pack(side=RIGHT, fill=BOTH, padx=20, pady=5)

        self.PROGRAMLOADframe.grid(row=15,
                                   column=9,
                                   rowspan=2,
                                   columnspan=4,
                                   sticky="wens")

# ==============================================================================

    def mkMemory(self, f):
        self.MEMORYframe = Frame(f)
        self.MEMORYframe.config(relief=GROOVE)
        self.MEMORYframe.config(borderwidth=2)

        E = Frame(self.MEMORYframe)

        self.CLEAR = self.mkButton(E, "ClearMem", 0, 0)
        self.RANDOM = self.mkButton(E, "RandomMem", 0, 1)
        self.READ = self.mkButton(E, "ReadMem", 1, 0)
        self.WRITE = self.mkButton(E, "WriteMem", 1, 1)
        self.BUSTOMEM = self.mkButton(E, "BusToMem", 2, 0, 1, 2)

        F = Frame(self.MEMORYframe)

        for i in Range8:
            L = Label(F, textvariable=self.MEMORY[i])
            L.config(relief=GROOVE,
                     borderwidth=2,
                     bg="black",
                     fg="yellow",
                     height=1)
            L.grid(row=0, column=i, sticky="wens", ipadx=5)

        E.pack(side=TOP)
        F.pack(side=BOTTOM)

        self.MEMORYframe.grid(row=18,
                              column=9,
                              rowspan=5,
                              columnspan=2,
                              sticky="wens")

# ==============================================================================

    def mkDataBus(self, f):
        self.DBframe = Frame(f)
        self.DBframe.config(relief=GROOVE)
        self.DBframe.config(borderwidth=2, bg="red")
        self.DBframe.grid(row=0, column=0, rowspan=1, \
                          columnspan=9, sticky="wens")

        self.databusLabel = Label(self.DBframe, text="Data\nBus", width=10)
        self.databusLabel.pack(side=LEFT)

        self.DATABUSbuttons = []
        for i in Range8:
            b = Button(self.DBframe, textvariable=self.DATABUS[i])
            b.pack(side=LEFT, fill=BOTH)
            self.DATABUSbuttons.append(b)

    def mkAddressBus(self, f):
        self.ABframe = Frame(f)
        self.ABframe.config(relief=GROOVE)
        self.ABframe.config(borderwidth=2, bg="red")
        self.ABframe.grid(row=26,
                          column=0,
                          rowspan=1,
                          columnspan=13,
                          sticky="wens")

        self.AddressBusLabel = Label(self.ABframe,
                                     text="Address\nBus",
                                     width=12)
        self.AddressBusLabel.pack(side=LEFT)

        self.ADDRESSBUSbuttons = []
        for i in Range16:
            b = Button(self.ABframe, textvariable=self.ADDRESSBUS[i])
            b.pack(side=LEFT, fill=BOTH, ipadx=2)
            self.ADDRESSBUSbuttons.append(b)

# ==============================================================================

    def mkALU(self, f):
        self.ALUframe = Frame(f)
        self.ALUframe.config(relief=GROOVE)
        self.ALUframe.config(borderwidth=2)

        self.mkFunctionChoice(self.ALUframe)
        self.mkStates(self.ALUframe)

        self.ALUframe.grid(row=23,
                           column=9,
                           rowspan=3,
                           columnspan=4,
                           sticky="wens")

    def mkFunctionChoice(self, f):
        self.FUNCTIONframe = Frame(f)
        self.FUNCTIONframe.config(relief=GROOVE)
        self.FUNCTIONframe.config(borderwidth=2)

        self.F0label = Label(self.FUNCTIONframe,
                             text="F0",
                             borderwidth=2,
                             relief=GROOVE)
        self.F0label.grid(row=0, column=0, sticky="wens", padx=5)

        self.F1label = Label(self.FUNCTIONframe,
                             text="F1",
                             borderwidth=2,
                             relief=GROOVE)
        self.F1label.grid(row=0, column=1, sticky="wens", padx=8)

        self.F2label = Label(self.FUNCTIONframe,
                             text="F2",
                             borderwidth=2,
                             relief=GROOVE)
        self.F2label.grid(row=0, column=2, sticky="wens", padx=5)

        self.FUNCTIONbuttons = []

        self.F0button = Button(self.FUNCTIONframe)
        self.F0button.config(textvariable=self.FUNCTION[0],
                             borderwidth=2,
                             relief=GROOVE)
        self.F1button = Button(self.FUNCTIONframe)
        self.F1button.config(textvariable=self.FUNCTION[1],
                             borderwidth=2,
                             relief=GROOVE)
        self.F2button = Button(self.FUNCTIONframe)
        self.F2button.config(textvariable=self.FUNCTION[2],
                             borderwidth=2,
                             relief=GROOVE)

        self.FUNCTIONbuttons.append(self.F0button)
        self.FUNCTIONbuttons.append(self.F1button)
        self.FUNCTIONbuttons.append(self.F2button)

        for i in Range3:
            self.FUNCTIONbuttons[i].grid(row=1,
                                         column=i,
                                         sticky="wens",
                                         padx=5)

        self.FUNCTIONframe.pack(side=LEFT, padx=8, pady=3)

    def mkStates(self, f):
        self.STATESframe = Frame(f)
        self.STATESframe.config(relief=GROOVE)
        self.STATESframe.config(borderwidth=2)

        self.CARRYtag = Label(self.STATESframe,
                              text=" carry ",
                              borderwidth=2,
                              relief=GROOVE)
        self.CARRYtag.grid(row=0, column=0, padx=5, pady=2, sticky="wens")

        self.ZEROtag = Label(self.STATESframe,
                             text="  zero ",
                             borderwidth=2,
                             relief=GROOVE)
        self.ZEROtag.grid(row=0, column=1, padx=5, pady=1, sticky="wens")

        self.SIGNtag = Label(self.STATESframe,
                             text="  sign ",
                             borderwidth=2,
                             relief=GROOVE)
        self.SIGNtag.grid(row=0, column=2, padx=5, pady=2, sticky="wens")

        self.CARRY = self.mkStringVar("0")
        self.ZERO = self.mkStringVar("0")
        self.SIGN = self.mkStringVar("0")

        self.CARRYlabel = Label(self.STATESframe,
                                textvariable=self.CARRY,
                                borderwidth=2,
                                relief=GROOVE)
        self.CARRYlabel.grid(row=1, column=0, padx=5, pady=2, sticky="wens")

        self.ZEROlabel = Label(self.STATESframe,
                               textvariable=self.ZERO,
                               borderwidth=2,
                               relief=GROOVE)
        self.ZEROlabel.grid(row=1, column=1, padx=5, pady=1, sticky="wens")

        self.SIGNlabel = Label(self.STATESframe,
                               textvariable=self.SIGN,
                               borderwidth=2,
                               relief=GROOVE)
        self.SIGNlabel.grid(row=1, column=2, padx=5, pady=2, sticky="wens")

        self.STATESframe.pack(side=RIGHT, padx=8, pady=3)

# ==============================================================================

    def mkTagLabels(self, f):
        self.ALabel = self.mkLabel(f, "A", 1, 0)
        self.BLabel = self.mkLabel(f, "B", 2, 0)
        self.BLabel.config(bg="black", fg="yellow")
        self.CLabel = self.mkLabel(f, "C", 3, 0)
        self.CLabel.config(bg="black", fg="yellow")
        self.DLabel = self.mkLabel(f, "D", 4, 0)
        self.M1Label = self.mkLabel(f, "M1", 5, 0)
        self.M2Label = self.mkLabel(f, "M2", 6, 0)
        self.XLabel = self.mkLabel(f, "X", 7, 0)
        self.YLabel = self.mkLabel(f, "Y", 8, 0)
        self.J1Label = self.mkLabel(f, "J1", 9, 0)
        self.J2Label = self.mkLabel(f, "J2", 10, 0)
        self.PC1Label = self.mkLabel(f, "PC1", 11, 0)
        self.PC2Label = self.mkLabel(f, "PC2", 12, 0)
        self.Inc1Label = self.mkLabel(f, "Inc1", 13, 0)
        self.Inc2Label = self.mkLabel(f, "Inc2", 14, 0)
        self.IncUnit1Label = self.mkLabel(f, "IncUnit1", 15, 0)
        self.IncUnit2Label = self.mkLabel(f, "IncUnit2", 16, 0)
        self.InstLabel = self.mkLabel(f, "Inst", 17, 0)
        self.addLabel = self.mkLabel(f, "ADD", 18, 0)
        self.incLabel = self.mkLabel(f, "INC", 19, 0)
        self.andLabel = self.mkLabel(f, "AND", 20, 0)
        self.orLabel = self.mkLabel(f, "OR", 21, 0)
        self.xorLabel = self.mkLabel(f, "XOR", 22, 0)
        self.notLabel = self.mkLabel(f, "NOT", 23, 0)
        self.shlLabel = self.mkLabel(f, "SHL", 24, 0)
        self.clrLabel = self.mkLabel(f, "CLR", 25, 0)

        self.functionTagLabelDictionary = { (0,0,0) : self.addLabel, \
                                 (0,0,1) : self.incLabel, \
                                 (0,1,0) : self.andLabel, \
                                 (0,1,1) : self.orLabel, \
                                 (1,0,0) : self.xorLabel, \
                                 (1,0,1) : self.notLabel, \
                                 (1,1,0) : self.shlLabel, \
                                 (1,1,1) : self.clrLabel \
                                 }

        for i in self.functionTagLabelDictionary.values():
            i.config(bg="black", fg="yellow")

# ==============================================================================

    def mkRegisterStringVars(self):
        self.FUNCTION = [self.mkStringVar("0") for unused_i in Range3]
        self.DATABUS = [self.mkStringVar("0") for unused_i in Range8]
        self.Inst = [self.mkStringVar("0") for unused_i in Range8]
        self.A = [self.mkStringVar("0") for unused_i in Range8]
        self.B = [self.mkStringVar("0") for unused_i in Range8]
        self.C = [self.mkStringVar("0") for unused_i in Range8]
        self.D = [self.mkStringVar("0") for unused_i in Range8]
        self.M1 = [self.mkStringVar("0") for unused_i in Range8]
        self.M2 = [self.mkStringVar("0") for unused_i in Range8]
        self.X = [self.mkStringVar("0") for unused_i in Range8]
        self.Y = [self.mkStringVar("0") for unused_i in Range8]
        self.J1 = [self.mkStringVar("0") for unused_i in Range8]
        self.J2 = [self.mkStringVar("0") for unused_i in Range8]
        self.PC1 = [self.mkStringVar("0") for unused_i in Range8]
        self.PC2 = [self.mkStringVar("0") for unused_i in Range8]
        self.Inc1 = [self.mkStringVar("0") for unused_i in Range8]
        self.Inc2 = [self.mkStringVar("0") for unused_i in Range8]
        self.IncUnit1 = [self.mkStringVar("0") for unused_i in Range8]
        self.IncUnit2 = [self.mkStringVar("0") for unused_i in Range8]
        self.Add = [self.mkStringVar("0") for unused_i in Range8]
        self.Inc = [self.mkStringVar("0") for unused_i in Range8]
        self.And = [self.mkStringVar("0") for unused_i in Range8]
        self.Or = [self.mkStringVar("0") for unused_i in Range8]
        self.Xor = [self.mkStringVar("0") for unused_i in Range8]
        self.Not = [self.mkStringVar("0") for unused_i in Range8]
        self.Shl = [self.mkStringVar("0") for unused_i in Range8]
        self.Clr = [self.mkStringVar("0") for unused_i in Range8]
        self.ADDRESSBUS = [self.mkStringVar("0") for unused_i in Range16]
        self.MEMORY = [self.mkStringVar("0") for unused_i in Range8]

# ==============================================================================

    def setRegisterLabelColor(self, L, bc, fc="black"):
        for i in L:
            i.config(bg=bc, fg=fc)

    def mkRegisterLabels(self, f):
        self.Alabels = self.mkLabelList(f, self.A, 1)
        self.setRegisterLabelColor(self.Alabels, "gray90")
        self.Blabels = self.mkLabelList(f, self.B, 2)
        self.setRegisterLabelColor(self.Blabels, "black", "yellow")
        self.Clabels = self.mkLabelList(f, self.C, 3)
        self.setRegisterLabelColor(self.Clabels, "black", "yellow")
        self.Dlabels = self.mkLabelList(f, self.D, 4)
        self.setRegisterLabelColor(self.Dlabels, "gray90")
        self.M1labels = self.mkLabelList(f, self.M1, 5)
        self.setRegisterLabelColor(self.M1labels, "gray90")
        self.M2labels = self.mkLabelList(f, self.M2, 6)
        self.setRegisterLabelColor(self.M2labels, "gray90")
        self.Xlabels = self.mkLabelList(f, self.X, 7)
        self.setRegisterLabelColor(self.Xlabels, "gray90")
        self.Ylabels = self.mkLabelList(f, self.Y, 8)
        self.setRegisterLabelColor(self.Ylabels, "gray90")

        self.J1labels = self.mkLabelList(f, self.J1, 9)
        self.J2labels = self.mkLabelList(f, self.J2, 10)
        self.PC1labels = self.mkLabelList(f, self.PC1, 11)
        self.PC2labels = self.mkLabelList(f, self.PC2, 12)

        self.Inc1labels = self.mkLabelList(f, self.Inc1, 13)
        self.setRegisterLabelColor(self.Inc1labels, "gray95")
        self.Inc2labels = self.mkLabelList(f, self.Inc2, 14)
        self.setRegisterLabelColor(self.Inc2labels, "gray95")

        self.IncUnit1labels = self.mkLabelList(f, self.IncUnit1, 15)
        self.setRegisterLabelColor(self.IncUnit1labels, "gray95")
        self.IncUnit2labels = self.mkLabelList(f, self.IncUnit2, 16)
        self.setRegisterLabelColor(self.IncUnit2labels, "gray95")

        self.Instlabels = self.mkLabelList(f, self.Inst, 17)

        self.addlabels = self.mkLabelList(f, self.Add, 18)
        self.setRegisterLabelColor(self.addlabels, "black", "red")
        self.inclabels = self.mkLabelList(f, self.Inc, 19)
        self.setRegisterLabelColor(self.inclabels, "black", "yellow")
        self.andlabels = self.mkLabelList(f, self.And, 20)
        self.setRegisterLabelColor(self.andlabels, "black", "yellow")
        self.orlabels = self.mkLabelList(f, self.Or, 21)
        self.setRegisterLabelColor(self.orlabels, "black", "yellow")
        self.xorlabels = self.mkLabelList(f, self.Xor, 22)
        self.setRegisterLabelColor(self.xorlabels, "black", "yellow")
        self.notlabels = self.mkLabelList(f, self.Not, 23)
        self.setRegisterLabelColor(self.notlabels, "black", "yellow")
        self.shllabels = self.mkLabelList(f, self.Shl, 24)
        self.setRegisterLabelColor(self.shllabels, "black", "yellow")
        self.clrlabels = self.mkLabelList(f, self.Clr, 25)
        self.setRegisterLabelColor(self.clrlabels, "black", "yellow")

        self.functionLabelsDictionary = { (0,0,0) : self.addlabels, \
                                 (0,0,1) : self.inclabels, \
                                 (0,1,0) : self.andlabels, \
                                 (0,1,1) : self.orlabels, \
                                 (1,0,0) : self.xorlabels, \
                                 (1,0,1) : self.notlabels, \
                                 (1,1,0) : self.shllabels, \
                                 (1,1,1) : self.clrlabels \
                                 }

# ===== Load & Select ==========================================================

    def mkLoad8Buttons(self, f):
        self.loadA = self.mkButton(f, "load A", 1, 9, 1, 2)
        self.loadB = self.mkButton(f, "load B", 2, 9, 1, 2)
        self.loadC = self.mkButton(f, "load C", 3, 9, 1, 2)
        self.loadD = self.mkButton(f, "load D", 4, 9, 1, 2)
        self.loadM1 = self.mkButton(f, "load M1", 5, 9, 1, 2)
        self.loadM2 = self.mkButton(f, "load M2", 6, 9, 1, 2)
        self.loadX = self.mkButton(f, "load X", 7, 9)
        self.loadY = self.mkButton(f, "load Y", 8, 9)
        self.loadJ1 = self.mkButton(f, "load J1", 9, 9, 1, 2)
        self.loadJ2 = self.mkButton(f, "load J2", 10, 9, 1, 2)

        self.loadInst = self.mkButton(f, "load Inst", 17, 9, 1, 2)

    def mkLoad16Buttons(self, f):
        self.loadXY = self.mkButton(f, "load XY", 7, 10, 2, 1)
        self.loadPC = self.mkButton(f, "load PC", 11, 9, 2, 2)
        self.loadINC = self.mkButton(f, "load INC", 13, 9, 2, 2)

    def mkSelect8Buttons(self, f):
        self.selectA = self.mkButton(f, "select A", 1, 11, 1, 2)
        self.selectB = self.mkButton(f, "select B", 2, 11, 1, 2)
        self.selectC = self.mkButton(f, "select C", 3, 11, 1, 2)
        self.selectD = self.mkButton(f, "select D", 4, 11, 1, 2)
        self.selectM1 = self.mkButton(f, "select M1", 5, 11)
        self.selectM2 = self.mkButton(f, "select M2", 6, 11)
        self.selectX = self.mkButton(f, "select X", 7, 11)
        self.selectY = self.mkButton(f, "select Y", 8, 11)

    def mkSelect16Buttons(self, f):
        self.selectM = self.mkButton(f, "select M", 5, 12, 2, 1)
        self.selectXY = self.mkButton(f, "select XY", 7, 12, 2, 1)
        self.selectJ = self.mkButton(f, "select J", 9, 11, 2, 2)
        self.selectPC = self.mkButton(f, "select PC", 11, 11, 2, 2)
        self.selectINC = self.mkButton(f, "select INC", 13, 11, 2, 2)

# ===== System Messages ========================================================

    def mkMessageArea(self, f):
        self.text = Text(f, height=36, width=64)
        self.text.configure(font=("Courier", 11, "bold"),
                            bg="black",
                            fg="green")
        self.scroll = Scrollbar(f, command=self.text.yview)
        self.text.configure(yscrollcommand=self.scroll.set)

        self.text.pack(side=LEFT, padx=3, pady=2)
        self.scroll.pack(side=RIGHT, fill=Y, padx=3, pady=2)

    def addText(self, text):
        self.text.insert(END, text + "\n")
        self.text.yview(END)

# ===== Initialization =========================================================

    def __init__(self):
        Tk.__init__(self)

        self.title("Virtual Machine")
        self.config(bg="blue")

        self.registers = LabelFrame(self, bg="blue")
        self.registers.config(relief=GROOVE)
        self.registers.config(borderwidth=2)
        self.registers.config(text="Virtual Machine: controls and states")
        self.registers.config(labelanchor="nw")
        self.registers.pack(side=LEFT, fill=BOTH)

        self.mkRegisterStringVars()

        self.mkTagLabels(self.registers)
        self.mkDataBus(self.registers)

        self.mkRegisterLabels(self.registers)

        self.mkLoad8Buttons(self.registers)
        self.mkLoad16Buttons(self.registers)
        self.mkSelect8Buttons(self.registers)
        self.mkSelect16Buttons(self.registers)

        self.mkAddressBus(self.registers)

        self.mkALU(self.registers)
        self.mkMemory(self.registers)
        self.mkProgramLoad(self.registers)
        self.mkProgramControl(self.registers)
        self.mkHaltArea(self.registers)

        self.messages = LabelFrame(self, bg="blue")
        self.messages.config(relief=GROOVE)
        self.messages.config(borderwidth=2)
        self.messages.config(text="Virtual Machine: system messages")
        self.messages.config(labelanchor="nw")
        self.messages.pack(side=RIGHT, fill=BOTH)

        self.mkMessageArea(self.messages)
    pixel = tk.PhotoImage(master=root, name='test_photo', width=1, height=1)

    colors = ['#00FF00', '#FF0000']
    for i in range(0, 20):
        rowFrame = Frame(scrolling_area.innerframe)
        rowFrame.pack()
        # rowFrame.config(width=20*20, height=20)
        # rowFrame.place(x=0, y=i*20)
        for j in range(0, 8):
            l = Label(rowFrame,
                      image=pixel,
                      text="Label %s, %s" % (str(i), str(j)),
                      bg=colors[(i + j) % 2])
            l.pack(side="left")
            l.config(width=40, height=20)
            # l.place(x=j*20, y=0)
            # l.place(x=j*20, y=i*20)

    def print_simple(event):
        print("In function 'print_simple'.")
        print("event: {}".format(event))

    l.bind('<Button-1>', print_simple)

    # scrolling_area.canvas.config()
    # scrolling_area.update_viewport()
    # scrolling_area.canvas.config(scrollregion=scrolling_area.canvas.bbox('all'))

    # scrolling_area.canvas.config(scrollregion=(0, 0, 8*20, 20*20))
    # scrolling_area.config(width=100, height=60)
Exemple #35
0
class Emulatore(object):

    """
    Interfaccia grafica per l'emulatore del pdp8
    """

    def __init__(self, master, codice, calcolatore, emulatore):
        """
        Inizializza i frame per l'interfaccia dell'emulatore
        """
        self.CD = calcolatore
        self.codice = codice
        self.delay = 100
        self.master = Frame(master)
        self.root = emulatore

        # Memoria Ram
        self.ram = LabelFrame(
            self.master, text='Memoria RAM', relief=RIDGE, borderwidth=5, labelanchor='n', pady=5)
        self.ram.rowconfigure(0, weight=1)
        self.ram.columnconfigure(0, weight=1)
        self.ram.grid(
            row=0, column=0, rowspan=3, columnspan=5, sticky=W + E + N + S)

        # Controlli
        self.controlli = Frame(self.master, padx=10, pady=10)
        self.controlli.grid(row=0, column=5, rowspan=1)

        # Status CD
        self.registri = LabelFrame(
            self.master, text='REGISTRI', relief=RIDGE, borderwidth=5, labelanchor='n', padx=25, pady=10)
        self.registri.grid(row=0, column=6, rowspan=1, sticky=W + E + N + S)
        self.unita = LabelFrame(
            self.master, text='UC', relief=RIDGE, borderwidth=5, labelanchor='n', padx=10, pady=10)
        self.unita.grid(row=2, column=6, rowspan=1, sticky=N)

        # Var
        self.variabili = Frame(self.master)
        self.variabili.grid(row=2, column=5)
        self.nstep = LabelFrame(
            self.variabili, text='Num. Step', relief=RIDGE, borderwidth=5, labelanchor='n')
        self.nstep.grid(row=0, column=5, sticky=W + E)
        self.delays = LabelFrame(
            self.variabili, text='Delay', relief=RIDGE, borderwidth=5, labelanchor='n')
        self.delays.grid(row=1, column=5, sticky=W + E)
        self.tempo = LabelFrame(
            self.variabili, text='Tempo', relief=RIDGE, borderwidth=5, labelanchor='n')
        self.tempo.grid(row=1, column=6, sticky=W + E)

        # Unita' di controllo
        self.unitas = LabelFrame(
            self.unita, text='S', labelanchor='s', padx=10)
        self.unitas.grid(row=0, column=0, sticky=N)
        self.unitaf = LabelFrame(
            self.unita, text='F', labelanchor='s', padx=10)
        self.unitaf.grid(row=0, column=1, sticky=N)
        self.unitar = LabelFrame(
            self.unita, text='R', labelanchor='s', padx=10)
        self.unitar.grid(row=0, column=2, sticky=N)
        self.unitaint = LabelFrame(
            self.unita, text='Int.', labelanchor='s', padx=10)
        self.unitaint.grid(row=0, column=3, sticky=N)

        # Registri
        self.programc = LabelFrame(
            self.registri, text='PC', relief=FLAT, labelanchor='e', padx=5)
        self.programc.grid(row=0, column=0, sticky=W + E)
        self.mar = LabelFrame(
            self.registri, text='MAR', relief=FLAT, labelanchor='e', padx=5)
        self.mar.grid(row=1, column=0, sticky=W + E)
        self.mbr = LabelFrame(
            self.registri, text='MBR', relief=FLAT, labelanchor='e', padx=5)
        self.mbr.grid(row=2, column=0, sticky=W + E)
        self.lopr = LabelFrame(
            self.registri, text='OPR', relief=FLAT, labelanchor='e', padx=5)
        self.lopr.grid(row=3, column=0, sticky=W + E)
        self.vari = LabelFrame(
            self.registri, text='I', relief=FLAT, labelanchor='e', padx=5)
        self.vari.grid(row=4, column=0, sticky=W + E)
        self.vare = LabelFrame(
            self.registri, text='E', relief=FLAT, labelanchor='e', padx=5)
        self.vare.grid(row=5, column=0, sticky=W + E)
        self.lac = LabelFrame(
            self.registri, text='AC', relief=FLAT, labelanchor='e', padx=5)
        self.lac.grid(row=6, column=0, sticky=W + E)
        self.lacint = LabelFrame(
            self.registri, text='INT AC', relief=FLAT, labelanchor='e', padx=5)
        self.lacint.grid(row=7, column=0, sticky=W + E)
        self.lachex = LabelFrame(
            self.registri, text='HEX AC', relief=FLAT, labelanchor='e', padx=5)
        self.lachex.grid(row=8, column=0, sticky=W + E)

        # Microistruzioni
        self.micro = LabelFrame(
            self.master, text='Microistruzioni eseguite', relief=RIDGE, borderwidth=5, labelanchor='n', pady=5)
        self.micro.rowconfigure(0, weight=1)
        self.micro.columnconfigure(0, weight=1)
        self.micro.grid(
            row=3, column=4, rowspan=5, columnspan=5, sticky=W + E + N + S)

        # Inout
        self.inout = LabelFrame(
            self.master, text='Input & Output', relief=RIDGE, borderwidth=5, labelanchor='n', pady=5)
        self.inout.rowconfigure(0, weight=1)
        self.inout.columnconfigure(0, weight=1)
        self.inout.grid(row=3, column=0, columnspan=4, sticky=W + E + N + S)

        self.create_widgets()

    def create_widgets(self):
        """
        Crea il layout del programma, finestra dell'emulatore
        """
        # Memoria RAM
        self.Visualizza = Text(self.ram, width=80)
        self.Visualizzascrollbar = Scrollbar(self.ram)
        self.Visualizzascrollbar.config(command=self.Visualizza.yview)
        self.Visualizza.config(yscrollcommand=self.Visualizzascrollbar.set)
        self.Visualizzascrollbar.grid(row=0, column=1, sticky=N + S)
        self.Visualizza.grid(row=0, column=0, sticky=W)

        # INOUT
        self.Visualizzainout = Text(
            self.inout, width=62, height=7, fg='green', bg='black')
        self.Visualizzascrollbar_inout = Scrollbar(self.inout)
        self.Visualizzascrollbar_inout.config(
            command=self.Visualizzainout.yview)
        self.Visualizzainout.config(
            yscrollcommand=self.Visualizzascrollbar_inout.set)
        self.Visualizzascrollbar_inout.grid(row=0, column=1, sticky=N + S)
        self.Visualizzainout.grid(row=0, column=0, sticky=W)

        # Mircroistruzioni
        self.Visualizzamicro = Text(self.micro, width=55, height=7)
        self.Visualizzascrollbar_m = Scrollbar(self.micro)
        self.Visualizzascrollbar_m.config(command=self.Visualizzamicro.yview)
        self.Visualizzamicro.config(
            yscrollcommand=self.Visualizzascrollbar_m.set)
        self.Visualizzascrollbar_m.grid(row=0, column=1, sticky=N + S)
        self.Visualizzamicro.grid(row=0, column=0, sticky=W)

        # Pulsanti
        self.butload = Button(
            self.controlli, text='LOAD', anchor=CENTER, width=15, command=self.loading, bg='SkyBlue')
        self.butload.grid(row=0, column=0)
        self.butstep = Button(
            self.controlli, text='Step', anchor=CENTER, width=15, command=self.step, bg='linen')
        self.butstep.grid(row=1, column=0)
        self.butminstep = Button(
            self.controlli, text='miniStep', anchor=CENTER, width=15, command=self.mini_step, bg='linen')
        self.butminstep.grid(row=2, column=0)
        self.butstep = Button(self.controlli, text='microStep',
                              anchor=CENTER, width=15, command=self.micro_step, bg='linen')
        self.butstep.grid(row=3, column=0)
        self.butsetstep = Button(
            self.controlli, text='Set n Step', anchor=CENTER, width=15, command=self.setnstep, bg='linen')
        self.butsetstep.grid(row=4, column=0)
        self.butsetdelay = Button(
            self.controlli, text='Set Delay', anchor=CENTER, width=15, command=self.setdelay, bg='linen')
        self.butsetdelay.grid(row=5, column=0)
        self.butstart = Button(
            self.controlli, text='START', anchor=CENTER, width=15, command=self.start, bg='DarkOliveGreen3')
        self.butstart.grid(row=6, column=0)
        self.butreset = Button(
            self.controlli, text='RESET', anchor=CENTER, width=15, command=self.resetCD, bg='Orange3')
        self.butreset.grid(row=7, column=0)
        self.butstop = Button(
            self.controlli, text='STOP', anchor=CENTER, width=15, command=self.stop, bg='IndianRed')
        self.butstop.grid(row=8, column=0)
        self.butbreak = Button(
            self.controlli, text='BREAK', anchor=CENTER, width=15, command=self.breakpoint, bg='Magenta2')
        self.butbreak.grid(row=9, column=0)
        self.butcontinue = Button(
            self.controlli, text='CONTINUA', anchor=CENTER, width=15, command=self.continua, bg='Magenta2')
        self.butcontinue.grid(row=10, column=0)
        self.butesegui = Button(
            self.controlli, text='ESEGUI', anchor=CENTER, width=15, command=self.esegui, bg='Yellow')
        self.butesegui.grid(row=11, column=0)

        # Labels
        self.labelprogramc = Label(
            self.programc, text='00000000000', relief=SUNKEN, bg='red')
        self.labelprogramc.grid()
        self.labelmar = Label(
            self.mar, text='00000000000', relief=SUNKEN, bg='yellow')
        self.labelmar.grid()
        self.labelmbr = Label(self.mbr, text='000000000000000', relief=SUNKEN)
        self.labelmbr.grid()
        self.labelvari = Label(self.vari, text='0', relief=SUNKEN)
        self.labelvari.grid()
        self.labelopr = Label(self.lopr, text='000', relief=SUNKEN)
        self.labelopr.grid()
        self.labelucs = Label(self.unitas, text='0')
        self.labelucs.grid()
        self.labelucf = Label(self.unitaf, text='0')
        self.labelucf.grid()
        self.labelucr = Label(self.unitar, text='0')
        self.labelucr.grid()
        self.labelucint = Label(self.unitaint, text='0')
        self.labelucint.grid()
        self.labelnstep = Label(self.nstep, text='1')
        self.labelnstep.grid()
        self.labeldelay = Label(self.delays, text=str(self.delay))
        self.labeldelay.grid()
        self.labeltempo = Label(self.tempo, text=str(self.CD.tempo))
        self.labeltempo.grid()
        self.labelac = Label(self.lac, text='000000000000000', relief=SUNKEN)
        self.labelac.grid()
        self.labelacint = Label(
            self.lacint, text='000000000000000', relief=SUNKEN)
        self.labelacint.grid()
        self.labelachex = Label(
            self.lachex, text='000000000000000', relief=SUNKEN)
        self.labelachex.grid()
        self.labelvare = Label(self.vare, text='0', relief=SUNKEN)
        self.labelvare.grid()

    def continua(self):
        """
        Continua l'esecuzione dopo un break
        """
        self.CD.S = True
        self.esegui()

    def micro_step(self):
        """
        Esegue il metodo step del calcolatore didattico ed aggiorna
        """
        if self.CD.S:
            self.CD.step(self.root, self.codice)
            if self.CD.tempo == 0 and not self.CD.F and not self.CD.R:
                self.CD.previstr = self.CD.nextistr
            self.aggiornaall()

    def step(self):
        """
        Esegue il metodo step del calcolatore didattico ed aggiorna
        """
        var = True
        if self.CD.S and self.CD.nstep > 0:
            while var and self.CD.S:
                self.CD.step(self.root, self.codice)
                if not self.CD.F and not self.CD.R and self.CD.tempo == 0:
                    self.CD.nstep -= 1
                    self.aggiornaall()
                    self.CD.previstr = self.CD.nextistr
                    var = False
            if self.CD.nstep > 0:
                self.butstep.after(self.delay, self.step)
            else:
                self.CD.setnstep(1)
        else:
            self.CD.setnstep(1)
            self.aggiornaall()

    def esegui(self):
        """
        Esegue il programma fino all'arresto della macchina tramite
        l'istruzione HLT
        """
        while self.CD.S:
            self.CD.step(self.root, self.codice)
            if not self.CD.F and not self.CD.R and self.CD.tempo == 0:
                self.aggiornaall()
                self.CD.previstr = self.CD.nextistr
                break
        if self.CD.S:
            self.butesegui.after(self.delay, self.esegui)
        else:
            self.CD.setnstep(1)
            self.aggiornaall()

    def mini_step(self):
        """
        Esegue un singolo ciclo della macchina
        """
        if self.CD.S:
            for x in range(0, 4):
                self.CD.step(self.root, self.codice)
                self.CD.nstep = 1
                self.aggiornaall()
            if self.CD.F is False and self.CD.R is False:
                self.CD.previstr = self.CD.nextistr

    def cerca_istr_prev(self):
        """
        Evidenzia di VERDE l'ultima istruzione eseguita
        """
        if self.CD.PC == '000000000000':
            return
        try:
            if self.CD.previstr == '' and int(self.CD.PC, 2) == self.CD.START:
                return
            else:
                pospc = str(3.0 + self.CD.previstr)
                self.Visualizza.tag_add(
                    "PISTR", str(pospc[:-1] + '16'),  str(pospc[:-1] + 'end'))
                self.Visualizza.tag_config("PISTR", background="green")
                self.Visualizza.see(pospc)
        except TypeError:
            pass  # Errore che si ottiene durante il reset del CD

    # NOTA : METODO NON NECESSARIO NEL PROGRAMMA FINALE
    # def cerca_istr_corr(self):
    #    """
    #    Evidenzia di verde l'istruzione che si dovrà eseguire
    #    """
    #    if self.CD.PC == '000000000000':
    #        return
    #    try:
    #        if int(self.CD.PC,2) == self.CD.START:
    # Inizio esecuzione del programma
    # Il PC e l'istruzione da eseguire sono allo stesso 'livello'
    #            pos = str(3.0)
    #            self.Visualizza.tag_add("ISTR", str(pos[0]+'.16'), str(pos[:-1]+'end'))
    #            self.Visualizza.tag_config("ISTR", background = "green")
    #        else:
    #            pospc = str(3.0 + self.CD.nextistr)
    #            self.Visualizza.tag_add("ISTR", str(pospc[:-1]+'16'),  str(pospc[:-1]+'end'))
    #            self.Visualizza.tag_config("ISTR", background = "green")
    #            self.Visualizza.see(pospc)
    #    except TypeError:
    # pass ## Errore che si ottiene durante il reset del CD

    def cerca_MAR(self):
        """
        Evidenzia di giallo l'indirizzo puntato dal MAR
        """
        try:
            pos = 3.0
            stringa = self.Visualizza.get(str(pos), 'end')
            while stringa[:12] != self.CD.MAR and int(pos) < len(self.CD.RAM) + 3 and len(self.CD.RAM) > 0:
                pos += 1
                stringa = self.Visualizza.get(str(pos), 'end')
            if int(pos) >= len(self.CD.RAM) + 3:
                return
            self.Visualizza.tag_add("MAR", pos, str(float(pos) + 0.12))
            self.Visualizza.tag_config("MAR", background="yellow")
        except TypeError:
            pass  # Errore che si ottiene durante il reset del CD

    def cerca_PC(self):
        """
        Evidenzia di rosso l'indirizzo puntato da PC
        """
        try:
            pos = 3.0
            stringa = self.Visualizza.get(str(pos), 'end')
            while stringa[:12] != self.CD.PC and int(pos) < len(self.CD.RAM) + 3 and len(self.CD.RAM) > 0:
                pos += 1
                stringa = self.Visualizza.get(str(pos), 'end')
            if int(pos) >= len(self.CD.RAM) + 3:
                return
            self.Visualizza.tag_add("PC", pos, str(float(pos) + 0.12))
            self.Visualizza.tag_config("PC", background="red")
        except TypeError:
            pass  # Errore che si ottiene durante il reset del CD

    def aggiornaout(self):
        """
        Aggiorna micro e input/output
        """
        self.aggiornamicro()
        self.aggiornainout()

    def aggiornamicro(self):
        """
        Aggiorna le microistruzioni eseguite
        """
        self.Visualizzamicro.delete(1.0, END)
        stringa = self.CD.microistruzioni
        self.Visualizzamicro.insert(INSERT, stringa)
        self.Visualizzamicro.see(END)

    def aggiornainout(self):
        """
        Aggiorna gli input ed output di sistema
        """
        self.Visualizzainout.delete(1.0, END)
        stringa = self.CD.inout
        self.Visualizzainout.insert(INSERT, stringa)
        self.Visualizzainout.see(END)

    def aggiornaram(self):
        """
        Aggiorna lo stato della RAM
        """
        self.Visualizza.delete(1.0, END)
        stringa = self.CD.statusRAM()
        self.Visualizza.insert(INSERT, stringa)
        self.cerca_MAR()
        self.cerca_PC()
        self.cerca_istr_prev()
        # self.cerca_istr_corr() #Non più necessaria nella versione finale

    def aggiornareg(self):
        """
        Aggiorna lo stato dei Registri
        """
        self.labelprogramc.config(text=self.CD.PC)
        self.labelmar.config(text=self.CD.MAR)
        self.labelmbr.config(text=self.CD.MBR)
        self.labelac.config(text=self.CD.AC)
        self.labelacint.config(text=str(self.CD.range(int(self.CD.AC, 2))))
        self.labelachex.config(
            text=str((hex(int(self.CD.AC, 2))[2:].upper())).zfill(4))
        self.labelvare.config(text=self.CD.E)
        self.labelvari.config(text=self.CD.I)
        self.labelopr.config(text=self.CD.OPR)

    def aggiornauc(self):
        """
        Aggiorna lo stato dell'unita' di controllo
        """
        if self.CD.S and not self.CD.breaks:
            self.labelucs.config(text=self.CD.S, bg='green')
            self.unitas.config(bg='green')
        elif not self.CD.S and self.CD.breaks:
            self.labelucs.config(text=self.CD.S, bg='Magenta2')
            self.unitas.config(bg='Magenta2')
        else:
            self.labelucs.config(text=self.CD.S, bg='red')
            self.unitas.config(bg='red')
        self.labelucf.config(text=self.CD.F)
        self.labelucr.config(text=self.CD.R)
        self.labelucint.config(text=self.CD.Interrupt)
        self.labeltempo.config(text=self.CD.tempo)

    def aggiornaall(self):
        """
        Aggiorna tutto
        """
        self.aggiornaram()
        self.aggiornareg()
        self.aggiornauc()
        self.aggiornamicro()
        self.aggiornaout()
        self.labelnstep.config(text=self.CD.nstep)

    def loading(self):
        """
        Carica il contenuto del codice assembly decodificandolo in binario
        nella RAM
        """
        contenuto = self.codice.Inserisci.get(1.0, END)
        if len(contenuto) > 1:
            self.resetCD()
            if self.CD.carica(contenuto.decode('ascii', 'ignore'), self) is not None:
                self.CD.S = 0
                self.aggiornaall()

    def resetCD(self):
        """
        Resetta il calcolatore didattico
        """
        self.CD = pdp8()
        self.aggiornaall()

    def start(self):
        """
        Mette la variabile Start (S) ad 1, cioe' True
        """
        self.CD.S = True
        if self.CD.breaks == True:
            self.CD.breaks = False
        self.aggiornauc()

    def stop(self):
        """
        Mette la variabile Start (S) ad 0, cioe' False
        """
        self.CD.S = False
        self.aggiornauc()

    def setnstep(self):
        """
        Setta, in base al valore passato, il numero di cicli da eseguire
        """
        temp = askinteger("Num Step", "Numero di step da eseguire",
                          initialvalue=1, minvalue=1, parent=self.root)
        if temp is None:
            self.CD.setnstep(1)
        else:
            self.CD.setnstep(temp)
            self.labelnstep.config(text=self.CD.nstep)

    def setdelay(self):
        """
        Setta, in base al valore passato, il ritardo di esecuzione.
        Il valore è espresso in millisecondi, di default = 1000
        """
        temp = askinteger("Set Delay", "Ritardo in millisecondi",
                          initialvalue=100, minvalue=1, parent=self.root)
        if temp is not None:
            self.delay = temp
            self.labeldelay.config(text=self.delay)

    def breakpoint(self):
        """
        Setta o elimina i breakpoint dal programma caricato in memoria
        """
        temp = askstring(
            "Cella di memoria", "Indirizzo esadecimale", parent=self.root)
        if temp is not None:
            temp = self.CD.binario(int(temp, 16)).zfill(12)
            self.CD.breakpoint(temp)
            self.aggiornaram()

    def exit(self):
        """
        Esce dal programma
        """
        if askquestion('Exit', 'Sicuro di voler uscire?', parent=self.master) == YES:
            self.codice.master.quit()
            self.codice.master.destroy()
        else:
            showinfo('Suggerimento', """Forse e' meglio fare una pausa!""",
                     icon=WARNING, parent=self.master)
class ChemicalProperties:
    """Gets the contaminant properties."""
    def __init__(self, master, system, database):
        """Constructor method. Defines the parameters to be obtained in this window."""

        self.master = master
        self.fonttype = system.fonttype
        self.version = system.version
        self.superfont = get_superfont(self.fonttype)  #superscript font
        self.tframe = Frame(master.tframe)
        self.frame = Frame(master.frame)
        self.bframe = Frame(master.bframe)
        self.top = None  #flag for existence of toplevel#

        self.system = system
        self.database = database
        self.diffunit = system.diffunit
        self.concunit = system.concunit
        self.concunits = system.concunits

        if system.chemicals is None:
            self.chemicals = []
            self.nchemicals = 0
        else:
            self.chemicals = system.chemicals
            self.nchemicals = system.nchemicals

    def make_widgets(self):
        """Make the widgets for the window."""

        self.bgcolor = self.frame.cget('bg')

        # Construct all label widgets used in the problem
        self.instructions = Label(
            self.tframe,
            text=
            ' Please provide the following chemical properties:                    '
        )

        self.blankcolumn = Label(self.tframe, text='', width=1)
        self.editcolumn = Label(self.tframe, text='', width=6)
        self.delcolumn = Label(self.tframe, text='', width=6)
        self.numbercolumn = Label(self.tframe, text='', width=6)
        self.namecolumn = Label(self.tframe, text='', width=18)
        self.MWcolumn = Label(self.tframe, text='', width=8)
        self.tempcolumn = Label(self.tframe, text='', width=10)
        self.Dwcolumn = Label(self.tframe, text='', width=16)
        self.Koccolumn = Label(self.tframe, text='', width=16)
        self.Kdoccolumn = Label(self.tframe, text='', width=18)
        self.Refcolumn = Label(self.tframe, text='', width=17)
        self.endcolumn = Label(self.tframe, text='', width=1)

        self.botblankcolumn = Label(self.frame, text='', width=1)
        self.boteditcolumn = Label(self.frame, text='', width=6)
        self.botdelcolumn = Label(self.frame, text='', width=6)
        self.botnumbercolumn = Label(self.frame, text='', width=6)
        self.botnamecolumn = Label(self.frame, text='', width=18)
        self.botMWcolumn = Label(self.frame, text='', width=8)
        self.bottempcolumn = Label(self.frame, text='', width=10)
        self.botDwcolumn = Label(self.frame, text='', width=16)
        self.botKoccolumn = Label(self.frame, text='', width=16)
        self.botKdoccolumn = Label(self.frame, text='', width=18)
        self.botRefcolumn = Label(self.frame, text='', width=17)
        self.botendcolumn = Label(self.frame, text='', width=1)

        self.numberlabel = Label(self.tframe, text='Number')
        self.namelabel = Label(self.tframe, text='Chemical name')
        self.MWlabel = Label(self.tframe, text='Molecular\n Weight')
        self.templabel = Label(self.tframe, text='Temperature')
        self.Dwlabel = Label(self.tframe,
                             text='Molecular diffusivity\n in water')
        self.Koclabel = Label(self.tframe,
                              text='Organic carbon\n partition coefficient')
        self.Kdoclabel = Label(
            self.tframe,
            text='Dissolved organic carbon\n partition coefficient')
        self.Reflabel = Label(self.tframe, text='Reference')

        self.tempunits = Label(self.tframe, text=unichr(176) + 'C')
        self.Dwunits = Label(self.tframe, text=self.diffunit)
        self.Kocunits = Label(self.tframe, text='log(L/kg)')
        self.Kdocunits = Label(self.tframe, text='log(L/kg)')

        self.blank1 = Label(self.frame, text=' ')
        self.blank2 = Label(self.bframe, text=' ')

        self.addwidget = Button(self.bframe,
                                text='Add chemicals',
                                command=self.addchemical,
                                width=20)

        #show the widgets on the grid
        self.instructions.grid(row=0,
                               column=0,
                               columnspan=9,
                               padx=1,
                               sticky='W')

        self.blankcolumn.grid(row=1, column=0, sticky='WE', padx=1, pady=1)
        self.editcolumn.grid(row=1, column=1, sticky='WE', padx=1, pady=1)
        self.delcolumn.grid(row=1, column=2, sticky='WE', padx=1, pady=1)
        self.numbercolumn.grid(row=1, column=3, sticky='WE', padx=1, pady=1)
        self.namecolumn.grid(row=1, column=4, sticky='WE', padx=1, pady=1)
        self.MWcolumn.grid(row=1, column=5, sticky='WE', padx=1, pady=1)
        self.tempcolumn.grid(row=1, column=6, sticky='WE', padx=1, pady=1)
        self.Dwcolumn.grid(row=1, column=7, sticky='WE', padx=1, pady=1)
        self.Koccolumn.grid(row=1, column=8, sticky='WE', padx=1, pady=1)
        self.Kdoccolumn.grid(row=1, column=9, sticky='WE', padx=1, pady=1)
        self.Refcolumn.grid(row=1, column=10, sticky='WE', padx=1, pady=1)
        self.endcolumn.grid(row=1, column=11, sticky='WE', padx=1, pady=1)

        self.numberlabel.grid(row=2, column=3, sticky='WE', padx=1, pady=1)
        self.namelabel.grid(row=2, column=4, sticky='WE', padx=1, pady=1)
        self.MWlabel.grid(row=2, column=5, sticky='WE', padx=1, pady=1)
        self.templabel.grid(row=2, column=6, sticky='WE', padx=1, pady=1)
        self.Dwlabel.grid(row=2, column=7, sticky='WE', padx=1, pady=1)
        self.Koclabel.grid(row=2, column=8, sticky='WE', padx=1, pady=1)
        self.Kdoclabel.grid(row=2, column=9, sticky='WE', padx=1, pady=1)
        self.Reflabel.grid(row=2, column=10, sticky='WE', padx=1, pady=1)

        self.tempunits.grid(row=3, column=6, sticky='WE', padx=1, pady=1)
        self.Dwunits.grid(row=3, column=7, sticky='WE', padx=1, pady=1)
        self.Kocunits.grid(row=3, column=8, sticky='WE', padx=1, pady=1)
        self.Kdocunits.grid(row=3, column=9, sticky='WE', padx=1, pady=1)

        self.updatechemicals()

    def updatechemicals(self):

        try:
            self.botblankcolumn.grid_forget()
            self.boteditcolumn.grid_forget()
            self.botdelcolumn.grid_forget()
            self.botnumbercolumn.grid_forget()
            self.botnamecolumn.grid_forget()
            self.botMWcolumn.grid_forget()
            self.bottempcolumn.grid_forget()
            self.botDwcolumn.grid_forget()
            self.botKoccolumn.grid_forget()
            self.botKdoccolumn.grid_forget()
            self.botRefcolumn.grid_forget()
            self.botendcolumn.grid_forget()
        except:
            pass

        chemicals_list = self.database.keys()
        for chemical in self.chemicals:
            if chemical.soluable == 1:
                try:
                    chemicals_list.remove(chemical.name)
                except:
                    pass

        self.addwidget.grid_forget()

        namelabellength = 18
        reflabellength = 18

        row = 0

        for chemical in self.chemicals:
            try:
                chemical.remove_chemicalwidgets()
            except:
                pass
            chemical.number = self.chemicals.index(chemical) + 1
            chemical.chemicalwidgets(self.frame, row, self.master)
            row = row + 1

            if namelabellength < chemical.namelabel.winfo_reqwidth() / 8:
                namelabellength = int(
                    chemical.namelabel.winfo_reqwidth() / 8) + 1
            if reflabellength < chemical.Reflabel.winfo_reqwidth(
            ) / 8 * 1.1424219345:
                reflabellength = int(
                    chemical.Reflabel.winfo_reqwidth() / 8 * 1.1424219345) + 1

        self.namecolumn.config(width=namelabellength)
        self.Refcolumn.config(width=reflabellength)
        self.botnamecolumn.config(width=namelabellength)
        self.botRefcolumn.config(width=reflabellength)

        self.botblankcolumn.grid(row=row,
                                 column=0,
                                 sticky='WE',
                                 padx=1,
                                 pady=1)
        self.boteditcolumn.grid(row=row, column=1, sticky='WE', padx=1, pady=1)
        self.botdelcolumn.grid(row=row, column=2, sticky='WE', padx=1, pady=1)
        self.botnumbercolumn.grid(row=row,
                                  column=3,
                                  sticky='WE',
                                  padx=1,
                                  pady=1)
        self.botnamecolumn.grid(row=row, column=4, sticky='WE', padx=1, pady=1)
        self.botMWcolumn.grid(row=row, column=5, sticky='WE', padx=1, pady=1)
        self.bottempcolumn.grid(row=row, column=6, sticky='WE', padx=1, pady=1)
        self.botDwcolumn.grid(row=row, column=7, sticky='WE', padx=1, pady=1)
        self.botKoccolumn.grid(row=row, column=8, sticky='WE', padx=1, pady=1)
        self.botKdoccolumn.grid(row=row, column=9, sticky='WE', padx=1, pady=1)
        self.botRefcolumn.grid(row=row, column=10, sticky='WE', padx=1, pady=1)
        self.botendcolumn.grid(row=row, column=11, sticky='WE', padx=1, pady=1)

        row = 0
        self.blank2.grid(row=row)
        row = row + 1
        if len(chemicals_list) > 0:
            self.addwidget.grid(row=row, columnspan=11)
            row = row + 1

        self.addwidget.bind('<Return>', self.addchemical)

        if self.nchemicals == 0: self.focusbutton = self.addwidget
        else: self.focusbutton = None

        self.master.geometry()
        self.master.center()

    def addchemical(self, event=None):

        self.nchemicals = self.nchemicals + 1
        self.chemicals.append(Chemical(self.nchemicals, soluable=1))

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                ChemicalEditor(self.top,
                               self.system,
                               self.chemicals[-1],
                               self.chemicals,
                               self.database,
                               editflag=0))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.chemicals[-1].get_chemical(self.top.window)
            else:
                self.chemicals.remove(self.chemicals[-1])
                self.nchemicals = self.nchemicals - 1

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatechemicals()

    def editchemical(self, number):

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                ChemicalEditor(self.top,
                               self.system,
                               self.chemicals[number - 1],
                               self.chemicals,
                               self.database,
                               editflag=1))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.chemicals[number - 1].get_chemical(self.top.window)

            if self.top is not None:
                self.top.destroy()
                self.top = None

        elif self.top is not None:
            tkmb.showerror(
                title=self.system.version,
                message=
                'Please close the existing parameter input window first.')
            self.top.tk.focus()

        self.updatechemicals()

    def deletechemical(self, number):

        if self.top is None:

            self.top = CapSimWindow(master=self.master, buttons=2)
            self.top.make_window(
                ChemicalDeleter(self.top, self.system,
                                self.chemicals[number - 1]))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.chemicals[number - 1].remove_chemicalwidgets()
                self.chemicals.remove(self.chemicals[number - 1])
                self.nchemicals = self.nchemicals - 1

            if self.top is not None:
                self.top.destroy()
                self.top = None

        self.updatechemicals()

    def error_check(self, event=None):
        """Finish and move on.  Checks that the number chemicals are less than the
        total number of chemicals in database."""

        error = 0
        if self.nchemicals == 0: error = 1

        return error

    def warning(self):

        tkmb.showerror(
            title=self.version,
            message=
            'No chemical has been selected, please add chemicals by pressing the button "Add chemicals"'
        )
        self.focusbutton = None
        self.master.tk.lift()
Exemple #37
0
class Interface():
    def __init__(self, init, speed):
        self.init_compt = init
        self.speed = speed

        self.window = Tk()
        self.title = self.window.title('IA Minoïde')
        self.window.geometry('500x200')

        self.lbl = Label(self.window)
        self.btn = Button(self.window)

        self.reinit()

        self.window.mainloop()

    def start(self):
        net = self.NETWORK.get()
        chk1 = self.chk_state1.get()
        try:
            value0 = int(self.txt1.get())
            value1 = int(self.txt2.get())
            value2 = int(self.txt3.get())
            self.terget = [value0, value1, value2]
        except:
            #Messagebox.showinfo('Attention/',
            #'Les valeurs entrées ne sont pas correctes !')
            return
        self.txt1.destroy()
        self.txt2.destroy()
        self.txt3.destroy()
        self.chk0.destroy()
        self.chk1.destroy()
        self.res = 'Coordonnées cible: ('\
            + str(value0) + ', ' + str(value1)\
            +", "+ str(value2) + ')'

        #robot = VrepPioneerSimulation()
        robot = Pioneer(rospy)
        HL_size = 10  # nbre neurons of Hiden layer
        network = NN(3, HL_size, 2)
        self.trainer = OnlineTrainer(robot, network)

        if net:
            with open('last_w.json') as fp:
                json_obj = json.load(fp)
            for i in range(3):
                for j in range(HL_size):
                    network.wi[i][j] = json_obj["input_weights"][i][j]
            for i in range(HL_size):
                for j in range(2):
                    network.wo[i][j] = json_obj["output_weights"][i][j]
            print('Check 0 True')
        else:
            print('Check 0 False')

        if chk1:
            print('Check 1 True')
            thread = threading.Thread(target=self.trainer.train,
                                      args=(self.terget, ))
            thread.start()
        else:
            print('Check 1 False')

        if net:
            self.window.after(1, self.loop)
        else:
            self.window.after(1, self.save_file)

    def save_file(self):
        self.txt = Entry(self.window, width=30)
        self.lbl.config(text='Give a name to the log file (default to last):')
        self.btn.config(text='Valider', command=self.loop)

        self.txt.grid(column=0, row=1)
        self.lbl.grid(column=0, row=0)
        self.btn.grid(column=0, row=2)

        try:
            self.file_name = self.txt.get()
        except:
            """Messagebox.showinfo('Attention/',
                                "Le nom de fichier n'est pas correct")"""
        if self.file_name == '':
            self.file_name = 'last'
        with open("logs/" + self.file_name + ".json", 'w') as f:
            print(self.trainer.log_file)
            json.dump(self.trainer.log_file, f)
        f.close()
        print('Graph values have been saved in ' + self.file_name +
              '.json file')

    def loop(self):

        self.lbl.config(text=self.res)
        self.btn.config(text='Stop', command=self.stop)
        try:
            self.txt.destroy()
        except:
            pass

        if self.arret == 1:
            self.arret = 0
            self.lbl.config(text='Arrêt')
            self.btn.config(text='Réinitialiser', command=self.reinit)
            return

        if self.compt <= 0:
            self.lbl.config(text='Time is over !')
            self.btn.config(text='Réinitialiser', command=self.reinit)
            return

        self.compt -= self.speed / 100

        self.window.after(1, self.loop)

    def stop(self):
        self.arret = 1

    def reinit(self):
        self.arret = 0
        self.compt = self.init_compt

        self.lbl.config(text='Saisissez les coordonnées:',
                        bg="blue",
                        fg="white",
                        width=20)
        self.lbl.grid(column=0, row=0)
        self.txt1Lbl = Label(self.window)
        self.txt1 = Entry(self.window, width=3)
        self.txt2 = Entry(self.window, width=3)
        self.txt3 = Entry(self.window, width=3)

        self.txt1Lbl.config(text='X', bg="red", fg="white", width=3)
        self.txt1Lbl.grid(column=0, row=1)
        #self.lbl.pack()
        #self.txt1Lbl.pack()
        self.txt1.grid(column=1, row=1)
        self.txt2.grid(column=1, row=2)
        self.txt3.grid(column=1, row=3)

        self.NETWORK = BooleanVar()
        self.chk_state1 = BooleanVar()
        self.NETWORK.set(False)
        self.chk_state1.set(False)  #set check state
        self.chk0 = Checkbutton(self.window,
                                text='Load previous network',
                                var=self.NETWORK)
        self.chk1 = Checkbutton(self.window, text='Learn', var=self.chk_state1)

        self.chk0.grid(column=2, row=1)
        self.chk1.grid(column=2, row=2)

        self.btn.config(text='Lancer', command=self.start)
        self.btn.grid(column=0, row=4)
def inicio(c):
    global ventana2, Labeli, Labelt, panel
    global img0, img1, imgF
    img0=PhotoImage(file="00.gif") # Reads photos
    img1=PhotoImage(file="11.gif")
    imgF=PhotoImage(file="FF.gif")
    
    if c:  
        ventana2=Toplevel(ventana)
        ventana2.title("MANITOR")
        ventana2.configure(bg="white")
        ventana2.geometry("1000x600+5+40")
    
        Labelt=Label(ventana2,text='BIENVENIDO ', # ventana2 TEXTO
                fg="black",bg="white",font=("Helvetica 36 "))
        ventana2.columnconfigure(0,weight=1)
        Labelt.grid(row=1,column=0)
        
        Labeli=Label(ventana2,image=img1) # ventana2 IMAGEN
        ventana2.columnconfigure(0,weight=1)
        ventana2.update()
        Labeli.grid(row=2,column=0)
        
    else:#Toda esta parte no es necesaria se podria borrar hasta el update, ya que es un estado inical que nunca se muestra igual que arriba
        Labelt.config(text='BIENVENIDO ')
        ventana2.update()
        Labeli=Label(ventana2,image=img1)
        ventana2.columnconfigure(0,weight=1)
        Labeli.grid(row=2,column=0)
        Labeli.config(image=img1)
        Labeli.image=img1
        ventana2.update()
    ventana.iconify() # Turns window into an icon

    while 1:

##        cur.execute("INSERT INTO manitor VALUES(nextval('usuario_sequence'), current_timestamp, ' inicio ')")
        Labeli.destroy()
        ventana2.update()
        Labelt.config(text='BIENVENIDO \n  Por favor moje sus manos con agua')
        ventana2.update()
        video000                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     ()
        ventana2.update()
        
        Labelt.config(text='Deposite jabón en la mano')
##        cur.execute("INSERT INTO manitor VALUES(nextval('usuario_sequence'), current_timestamp, ' nuevo usuario ')")
        ventana2.update()

        def cero():
            b,auxType = contadorMovimiento.funcionMovimientoEnRegion(y[1],3,2,lower,upper) 
            instruction = falseType(b,auxType,Labelt,Labeli,img0,imgF)
            if not instruction:
                inicio(0)
                
        Thread(target=cero).start()
        Thread(target=video00()).start()

######################## instruccion 1
        
        Labeli.destroy()
        Labelt.config(text='Frote las palmas de las manos \n entre sí')
        ventana2.update()

        def primero():
            d,auxType = contadorMovimiento.funcionMovimientoEnRegion(y[1],3,2,lower,upper) 
            instruction = falseType(d,auxType,Labelt,Labeli,img0,imgF)
            if not instruction:
                inicio(0)
                
        Thread(target=primero).start()
        Thread(target=video1()).start()

########################## instruccion2
##
##        Labeli.destroy()
##        Labelt.config(text='Frote la palma de la mano derecha \n contra el dorso de la mano izquierda  \n entrelazando los dedos y viceversa')
##        panel = Label(ventana2)

##        def segundo():
##            e,auxType = contadorMovimiento.funcionMovimientoEnRegion(y[1],10,2,lower,upper) 
##            instruction = falseType(e,auxType,Labelt,Labeli,img0,imgF)
##            if not instruction:
##                inicio(0)
##                
##        Thread(target=segundo).start()
##        Thread(target=video1()).start()
##        
##        time.sleep(10)

######################## fin instrucciones
##
        Labeli=Label(ventana2,image=img12)
        ventana2.columnconfigure(0,weight=1)
        Labeli.grid(row=2,column=0)
        ventana2.update()
        Labelt.config(text='Sus manos son seguras')
##        Labeli.config(image=img12)
##        Labeli.image=img12
        ventana2.update()
        time.sleep(5)
Exemple #39
0
class Menu():
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        self.constructWindow()
        pass  # end construct

    '''
    creates the main menu window
    '''

    def constructWindow(self):
        self.frm_menu = Tk()
        self.frm_menu.geometry('400x450+0+0')
        self.frm_menu.title('Main Menu')
        self.frm_menu.resizable(False, False)

        Label(self.frm_menu, text="ATM Menu", font=("Courier", 30)).pack()
        Label(self.frm_menu,
              text="Select Your Transaction",
              font=("Courier", 10)).pack()
        self.lbl_menu = Label(self.frm_menu,
                              text="Account # 0123456789",
                              font=("Courier", 10))
        self.lbl_menu.pack()

        depositor = Depositor.getInstance()
        assert isinstance(depositor, Depositor)
        self.lbl_menu.config(text="Account # " + depositor.getAccountNumber())
        '''
        buttons
        '''
        self.img_deposit = PhotoImage(file="img_deposit.gif")
        self.btn_deposit = Button(self.frm_menu,
                                  text="Deposit",
                                  anchor='w',
                                  font=("Courier", 10),
                                  bg='#FFFFFF',
                                  image=self.img_deposit,
                                  compound='left',
                                  command=lambda: self.onDeposit())
        self.btn_deposit.pack(fill=X, padx=10)

        #
        self.img_withdraw = PhotoImage(file="img_withdraw.gif")
        self.btn_withdraw = Button(self.frm_menu,
                                   text="Withdraw",
                                   anchor='w',
                                   font=("Courier", 10),
                                   bg='#FFFFFF',
                                   image=self.img_withdraw,
                                   compound='left',
                                   command=lambda: self.onWithraw())
        self.btn_withdraw.pack(fill=X, padx=10)
        #
        self.img_balance = PhotoImage(file="img_balance.gif")
        self.btn_balance = Button(self.frm_menu,
                                  text="Balance Inquiry",
                                  anchor='w',
                                  font=("Courier", 10),
                                  bg='#FFFFFF',
                                  image=self.img_balance,
                                  compound='left',
                                  command=lambda: self.onBalance())
        self.btn_balance.pack(fill=X, padx=10)
        #
        self.img_change = PhotoImage(file="img_change_pin.gif")
        self.btn_changepin = Button(self.frm_menu,
                                    text="Change Pin",
                                    anchor='w',
                                    font=("Courier", 10),
                                    bg='#FFFFFF',
                                    image=self.img_change,
                                    compound='left',
                                    command=lambda: self.onPinChange())
        self.btn_changepin.pack(fill=X, padx=10)
        #
        self.img_view = PhotoImage(file="img_view_account.gif")
        self.btn_view = Button(self.frm_menu,
                               text="View Account",
                               anchor='w',
                               font=("Courier", 10),
                               bg='#FFFFFF',
                               image=self.img_view,
                               compound='left',
                               command=lambda: self.onViewInfo())
        self.btn_view.pack(fill=X, padx=10)
        #
        self.img_end = PhotoImage(file="img_end_transaction.gif")
        self.btn_end = Button(self.frm_menu,
                              text="End Transaction",
                              anchor='w',
                              font=("Courier", 10),
                              bg='#FFFFFF',
                              image=self.img_end,
                              compound='left',
                              command=lambda: self.onEndTransaction())
        self.btn_end.pack(fill=X, padx=10)
        '''
        display the window
        '''
        self.frm_menu.mainloop()
        pass  #end

    '''
    button events
    '''

    def verify(self):
        try:
            verify = popupWindow(self.frm_menu)
            self.frm_menu.wait_window(verify.top)

            depositor = Depositor.getInstance()
            assert isinstance(depositor, Depositor)

            if (verify.value == depositor.getPinCode()):
                return True
            else:
                Message.info("Wrong Pin Code")
                return False

        except:
            Message.info("Transaction Cancelled")
            return False
            pass
        pass

    #
    def onDeposit(self):
        print "deposit"

        if self.verify():
            DepositWindow()
        pass  # end func

    def onWithraw(self):
        print "withdraw"
        if self.verify():
            WithdrawWindow()
        pass  #end func

    def onBalance(self):
        print "balance"
        if self.verify():
            BalanceWindow()
        pass  #end func

    def onViewInfo(self):
        print "view"
        if self.verify():
            ViewWindow()
        pass  #end func

    def onPinChange(self):
        if self.verify():
            ChangePinWindow()
        print "change"
        pass  #end func

    def onEndTransaction(self):
        print "end"
        depositor = Depositor.getInstance()
        assert isinstance(depositor, Depositor)

        depositor.clearFields()

        self.frm_menu.destroy()
        HomeScreen()
        pass  #end func

    pass  # end class
Exemple #40
0
        pass
    else:
        foodl = 'Error..'
    label.config(text=foodl)


#主窗口
top = Tk()
top.title('compute')

ft = Font(family=('Verdana'), size=8)  #字体
#注册组件
text = Entry(top, font=ft)
button = Button(top, text='计算(注意先后运算)', command=pp)
label = Label(text='运算符: + - * / % **', font=ft)

Enter = lambda x: x.keycode == 13 and pp()

Key = lambda x: label.config(text='运算符: + - * / % **')

text.bind('<Key>', Enter)  #回车事件
text.focus()  #获得焦点

#

text.bind('<Button-1>', Key)
text.pack()
button.pack()
label.pack()
mainloop()
class AVA:
    def __init__(self, master):
        self.master = master
        master.title("PWMAVA")

        frame = Frame(master)
        frame.grid(row=0, column=0)

        #current status
        self.time_label = Label(frame)
        self.temp_label = Label(frame)
        self.elapsed_label = Label(frame)

        #current pwm values
        self.white_pwm = 0
        self.blue_pwm = 0
        self.red_pwm = 0
        self.uv_pwm = 0
        self.ir_pwm = 0
        self.entered_pwm = 0

        self.white_pwm_label_text = IntVar()
        self.white_pwm_label_text.set(self.white_pwm)
        self.blue_pwm_label_text = IntVar()
        self.blue_pwm_label_text.set(self.blue_pwm)
        self.red_pwm_label_text = IntVar()
        self.red_pwm_label_text.set(self.red_pwm)
        self.uv_pwm_label_text = IntVar()
        self.uv_pwm_label_text.set(self.uv_pwm)
        self.ir_pwm_label_text = IntVar()
        self.ir_pwm_label_text.set(self.ir_pwm)

        #adjustable pwm labels
        self.white_pwm_label = Label(master,
                                     textvariable=self.white_pwm_label_text)
        self.blue_pwm_label = Label(master,
                                    textvariable=self.blue_pwm_label_text)
        self.red_pwm_label = Label(master,
                                   textvariable=self.red_pwm_label_text)
        self.uv_pwm_label = Label(master, textvariable=self.uv_pwm_label_text)
        self.ir_pwm_label = Label(master, textvariable=self.ir_pwm_label_text)

        #static labels
        self.white_label = Label(master, text="Current White PWM:")
        self.blue_label = Label(master, text="Current Blue PWM:")
        self.red_label = Label(master, text="Current Red PWM:")
        self.uv_label = Label(master, text="Current UV PWM:")
        self.ir_label = Label(master, text="Current IR PWM:")

        #validation
        vcmd = master.register(self.validate)
        self.entry = Entry(master,
                           validate="key",
                           validatecommand=(vcmd, '%P'))

        #buttons
        self.enter_white_button = Button(master,
                                         text="Enter White PWM",
                                         command=lambda: self.update("white"))
        self.enter_blue_button = Button(master,
                                        text="Enter Blue PWM",
                                        command=lambda: self.update("blue"))
        self.enter_red_button = Button(master,
                                       text="Enter Red PWM",
                                       command=lambda: self.update("red"))
        self.enter_uv_button = Button(master,
                                      text="Enter UV PWM",
                                      command=lambda: self.update("uv"))
        self.enter_ir_button = Button(master,
                                      text="Enter IR PWM",
                                      command=lambda: self.update("ir"))
        self.reset_button = Button(master,
                                   text="Turn Off All",
                                   command=lambda: self.update("reset"))

        #layouts
        self.time_label.grid(row=0, column=0)
        self.elapsed_label.grid(row=0, column=1)
        self.temp_label.grid(row=0, column=2)

        self.white_label.grid(row=1, column=0, sticky=W)
        self.blue_label.grid(row=2, column=0, sticky=W)
        self.red_label.grid(row=3, column=0, sticky=W)
        self.uv_label.grid(row=4, column=0, sticky=W)
        self.ir_label.grid(row=5, column=0, sticky=W)
        self.white_pwm_label.grid(row=1, column=1, columnspan=1, sticky=E)
        self.blue_pwm_label.grid(row=2, column=1, columnspan=1, sticky=E)
        self.red_pwm_label.grid(row=3, column=1, columnspan=1, sticky=E)
        self.uv_pwm_label.grid(row=4, column=1, columnspan=1, sticky=E)
        self.ir_pwm_label.grid(row=5, column=1, columnspan=1, sticky=E)

        self.entry.grid(row=6, column=0, columnspan=3,
                        sticky=W + E)  #entry bar
        self.enter_white_button.grid(row=7, column=0, sticky=W + E)
        self.enter_blue_button.grid(row=8, column=0, sticky=W + E)
        self.enter_red_button.grid(row=9, column=0, sticky=W + E)
        self.enter_uv_button.grid(row=10, column=0, sticky=W + E)
        self.enter_ir_button.grid(row=11, column=0, sticky=W + E)
        self.reset_button.grid(row=12, column=0, sticky=W + E)

        self.timer_interval = 500  #500ms
        self.log_count = 2  #take log every second

        with open("LoggingData/log" + start_time.strftime("%m%d%Y-%H%M%S") +
                  ".csv",
                  mode="w") as log_file:
            ava_writer = csv.writer(log_file,
                                    delimiter=',',
                                    quotechar='"',
                                    quoting=csv.QUOTE_MINIMAL)
            ava_writer.writerow([
                "Date", "Time", "Temperature", "WHITEPWM", "BLUEPWM", "REDPWM",
                "UVPWM", "IRPWM"
            ])

        self.stat_update()

    def validate(self, new_text):
        if not new_text:
            self.entered_pwm = 0
            return True
        try:
            if int(new_text) < 0:
                return False
            if int(new_text) > 100:
                return False
            self.entered_pwm = int(new_text)
            return True
        except ValueError:
            return False

    def update(self, method):
        if method == "white":
            self.white_pwm = self.entered_pwm
            print("Pwm will now change for white!")
        if method == "blue":
            self.blue_pwm = self.entered_pwm
            print("Pwm will now change for blue!")
        if method == "red":
            self.red_pwm = self.entered_pwm
            print("Pwm will now change for red!")
        if method == "uv":
            self.uv_pwm = self.entered_pwm
            print("Pwm will now change for uv!")
        if method == "ir":
            self.ir_pwm = self.entered_pwm
            print("Pwm will now change for ir!")
        elif method == "reset":
            self.blue_pwm = self.entered_pwm
            self.white_pwm = self.entered_pwm
            self.red_pwm = self.entered_pwm
            self.uv_pwm = self.entered_pwm
            self.ir_pwm = self.entered_pwm
            print("Turn off!")

        self.white_pwm_label_text.set(self.white_pwm)
        self.blue_pwm_label_text.set(self.blue_pwm)
        self.red_pwm_label_text.set(self.red_pwm)
        self.uv_pwm_label_text.set(self.uv_pwm)
        self.ir_pwm_label_text.set(self.ir_pwm)
        self.entry.delete(0, END)

    def log_data(self, date, time, temperature, white, blue, red, uv, ir):
        with open("LoggingData/log" + start_time.strftime("%m%d%Y-%H%M%S") +
                  ".csv",
                  mode="a") as log_file:
            ava_writer = csv.writer(log_file,
                                    delimiter=',',
                                    quotechar='"',
                                    quoting=csv.QUOTE_MINIMAL)
            ava_writer.writerow(
                [date, time, temperature, white, blue, red, uv, ir])

    def change_pwm(self, white_duty, blue_duty, red_duty, uv_duty, ir_duty,
                   check_temp):
        if check_temp > 82:
            pwm_w.ChangeDutyCycle(0)
            pwm_b.ChangeDutyCycle(0)
            pwm_r.ChangeDutyCycle(0)
            pwm_uv.ChangeDutyCycle(0)
            pwm_ir.ChangeDutyCycle(0)

        else:
            pwm_w.ChangeDutyCycle(white_duty)
            pwm_b.ChangeDutyCycle(blue_duty)
            pwm_r.ChangeDutyCycle(red_duty)
            pwm_uv.ChangeDutyCycle(uv_duty)
            pwm_ir.ChangeDutyCycle(ir_duty)

    def stat_update(self):
        time = datetime.datetime.now()
        time_label = time.strftime("Time: %H:%M:%S")
        elapsed_time = str(time - start_time)
        temperature = (sensor.getTemp() - 32.0) * 5 / 9
        temperature_label = "Temperature: " + str(temperature)

        self.time_label.config(text=time_label)
        self.elapsed_label.config(text="Elapsed Time: " + elapsed_time[:10])
        self.temp_label.config(text=temperature_label)

        self.change_pwm(self.white_pwm, self.blue_pwm, self.red_pwm,
                        self.uv_pwm, self.ir_pwm, temperature)

        if (self.log_count > 2):
            self.log_data(time.strftime("%m-%d-%Y"), time.strftime("%H:%M:%S"),
                          temperature, self.white_pwm, self.blue_pwm,
                          self.red_pwm, self.uv_pwm, self.ir_pwm)
            self.log_count = 0
        self.log_count = self.log_count + 1

        self.master.after(self.timer_interval, self.stat_update)
Exemple #42
0
class calculadora(object):
    def __init__(self):

        # DEFINIR VARIABLES GENERALES
        self.maxprec = 20000  # Precision numérica de la calculadora - Dev:1000, Prd: 20000
        self.debuguear = 1  # Debug. Muestra en pantalla lo que se envia al display
        self.sendToDisplay = 0  # Enviar dígitos a Display (on/off)
        self.ard_comm = 'COM3'  # Serial com port, debe coincidir con los baudios y el puerto arduino
        self.ard_baud = 9600  # Serial baud rate, debe coincidir con los baudios y el puerto arduino
        self.ard_tiot = 0.1  # Serial timeout 100ms, testeado con arduino UNO
        self.fullscreen = 0  # Abrir en pantalla completa. Dev: 0, Prd: 1
        self.ultrawidescreen = 0  # Monitor UltraWideScreen

    def iniciar(self, master):
        ######### VARIABLES GENERALES #########
        # Velocidad (lista de velocidades en milisegundos)
        self.velist = [1000, 700, 500, 400, 300, 200, 150, 100]
        self.velmax = len(self.velist) - 1
        self.vel = -1
        self.memvel = 0

        # Debug
        self.porcionlen = 70  # Porcion a mostrar
        self.porcion = ''
        self.playsounds = 0  # VERSION DE PRUEBA!!
        self.playwaves = 1  # VERSION DE PRUEBA!!

        #Arduino COMM (Display)
        if self.sendToDisplay > 0:
            # debe coincidir con los baudios y el puerto arduino
            self.arduino = serial.Serial(self.ard_comm,
                                         self.ard_baud,
                                         timeout=self.ard_tiot)
            time.sleep(1)
            if self.sendToDisplay > 0:
                self.arduino.write('N')  # RESET DYSPLAY
                time.sleep(1)

        # nsp class
        self.nsp = NumericStringParser()
        self.nsp.setPresicion(self.maxprec)  #Set presicion

        # Contador de envio a Arduino
        self.resultadoAduino = ''
        self.resultadoNormal = ''
        self.contador = -1
        self._job = None

        #######################################
        if self.playwaves > 0:
            p = mu.pyaudio.PyAudio()

            self.stream = p.open(format=mu.pyaudio.paFloat32,
                                 channels=mu.CHANNELS,
                                 rate=mu.RATE,
                                 output=True,
                                 stream_callback=mu.callback)

            self.stream.stop_stream()
        #######################################

        self.master = master
        if self.fullscreen > 0:
            # Full screen
            master.overrideredirect(True)
            master.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(),
                                                 root.winfo_screenheight()))
            master.focus_set()  # <-- move focus to this widget
            # Otra opción
            # master.attributes('-fullscreen', True)
        else:
            master.geometry("%dx%d+0+0" % (master.winfo_screenwidth() - 16,
                                           master.winfo_screenheight() - 80))

        master.title("Calculadora")

        master.bind("<Escape>", lambda e: e.widget.quit())  # Python 2
        master.bind("<Key>", self.recibeChar)

        self.dondestoy = 'p'

        # Dividendo p
        self.dividendostr = ""
        self.dividendo = StringVar()
        self.dividendo.set(self.dividendostr)
        if self.ultrawidescreen > 0:
            # UltraWide Screen
            self.labelp = Label(master,
                                textvariable=self.dividendo,
                                bg="#fd0",
                                width=18,
                                justify="center",
                                font=("Roboto", 192))
        else:
            # 16:9 Screen
            self.labelp = Label(master,
                                textvariable=self.dividendo,
                                bg="#fd0",
                                width=21,
                                justify="center",
                                font=("Roboto", 96))

        self.line = Canvas(master, width=master.winfo_screenwidth(), height=50)
        # self.line.create_rectangle(0, 0, master.winfo_screenwidth(), 20, outline="#000", fill="#000")
        self.line.create_line(0,
                              0,
                              master.winfo_screenwidth(),
                              0,
                              fill="#000",
                              width=50)

        # Divisor q
        self.divisorstr = "1"
        self.divisor = StringVar()
        self.divisor.set(self.divisorstr)
        if self.ultrawidescreen > 0:
            # UltraWide Screen
            self.labelq = Label(master,
                                textvariable=self.divisor,
                                bg="#eee",
                                fg="#aaa",
                                width=18,
                                justify="center",
                                font=("Roboto", 192))
        else:
            # 16:9 Screen
            self.labelq = Label(master,
                                textvariable=self.divisor,
                                bg="#eee",
                                fg="#aaa",
                                width=21,
                                justify="center",
                                font=("Roboto", 96))

        # Resultado res
        self.resultastr = ""
        self.resulta = StringVar()
        self.resulta.set(self.resultastr)
        if self.ultrawidescreen > 0:
            # UltraWide Screen
            self.labelr = Label(master,
                                textvariable=self.resulta,
                                bg="#eee",
                                width=213,
                                justify="left",
                                font=("Roboto", 16))
        else:
            # 16:9 Screen
            self.labelr = Label(master,
                                textvariable=self.resulta,
                                bg="#eee",
                                width=120,
                                justify="left",
                                font=("Roboto", 16))

        # Posiciona
        self.line.place(relx=0, rely=.495)
        self.labelp.place(relx=0, rely=.22)
        self.labelq.place(relx=0, rely=.545)
        self.labelr.place(relx=0, rely=.80)

        # init timer de envio a arduino
        # self.onUpdate()

        #######################################
    def filtrar(self, s):
        if '.' in s:
            r = {
                '1': 'A',
                '2': 'B',
                '3': 'C',
                '4': 'D',
                '5': 'E',
                '6': 'F',
                '7': 'G',
                '8': 'H',
                '9': 'I',
                '0': 'J'
            }
            s = s.split('.')
            c = s[0][-1:]
            s[0] = s[0][0:-1]
            return s[0] + r[c] + s[1]
        else:
            return s

    def modcad(self, cad, c):
        cad = cad.decode('utf-8')
        p = cad[-1:]
        if isinstance(c, int):
            if (len(cad) >= c):
                cad = cad[:-c]
        else:
            c = c.decode('utf-8')
            cad = cad + c
        cad = cad.encode('utf-8')
        return cad

    def recibeChar(self, event):
        k = event.keycode
        c = event.char
        p = str(self.dividendostr)
        q = str(self.divisorstr)

        # # Test input del teclado
        # self.resultastr = c+': ',str(k)+': '+str(event.state)
        # self.resulta.set(self.resultastr)
        # return

        if self.debuguear == 0:
            self.resultastr = ''
            self.resulta.set(self.resultastr)

        numrs = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        if (self.dondestoy == 'q'):
            cadena = q
            # if cadena=='1':
            #     cadena = ''
        else:
            cadena = p
        # SALIDAS
        if c == 'c':  # c
            # reiniciar programa
            self.calculadora('REINICIAR', '', p, q)
            return
            # return '','REINICIAR'
        elif c == 'k':  # k
            # salir del programa
            self.calculadora('SALIR', '', p, q)
            return
            # return '','SALIR'

        # AVANZAR Y STOP
        if c == 'a':  # Avanza/Acelera
            if self.vel < 0 and self.resultadoAduino != '':
                self.vel = 0
                self.calcelUpdate('Avanzar')
                self.onUpdate()
            elif self.vel < self.velmax:
                self.vel = self.vel + 1
            return
            # return '','REINICIAR'
        elif c == 's':  # Stop
            if self.vel >= 0:
                self.vel = self.vel - 1
            return

        # IGUAL A
        elif k == 10 or k == 13 or c == 'i':  # or k==61: # [ENTER] o [=] > Salto de línea o igual: '\n' ó '\r' ó '='
            # imprimir cadena RESULTADO
            self.calculadora('RESULTADO', cadena, p, q)
            return
            # return cadena,'RESULTADO'

        # ESCRITURA NORMAL
        elif k == 8 or c == 'x':  # BACKSPACE
            # recortar cadena un digito
            cadena = self.modcad(cadena, 1)
        elif c in numrs:  # NUMEROS 0-9
            # incrementa la cadena con c
            cadena = self.modcad(cadena, str(c))
        # elif c==',' or c=='.': # COMA o PUNTO
        #     c='.' # Siempre usa punto
        #     # incrementa la cadena con c
        #     cadena = self.modcad(cadena,str(c))

        # NUMEROS ESPECIALES e y pi
        elif c == 'e':  # e => 101
            # Euler's number => 'e'
            c = 'e'
            # incrementa la cadena con c
            cadena = self.modcad(cadena, str(c))
        elif c == 'h':  # h => 104
            # PI => 'h'
            c = 'π'
            # incrementa la cadena con c
            cadena = self.modcad(cadena, str(c))
        elif c == 'f':  # f => 104
            # PI => 'h'
            c = 'φ'
            # incrementa la cadena con c
            cadena = self.modcad(cadena, str(c))

        # OPERACIONES SIMPLES: * + - /
        elif c == '*':  # * => 42
            # Multiplicación => Reemplaza asterisco con signo de multiplicacion ×
            c = '×'
            # incrementa la cadena con c
            cadena = self.modcad(cadena, str(c))
        elif c == '+' or c == 'm':  # + => 43
            # incrementa la cadena con c
            c = '+'
            cadena = self.modcad(cadena, str(c))
        elif c == '-' or c == 'n':  # - => 45
            # incrementa la cadena con c
            c = '-'
            cadena = self.modcad(cadena, str(c))
        elif c == 'r':  # r
            # SQRT => 'r'
            rcadena = cadena[::-1]
            if '(' in rcadena:
                if ')' in rcadena:
                    ax = rcadena.index('(')
                    cx = rcadena.index(')')
                    if ax < cx:
                        c = ')'
                    else:
                        c = '√('
                else:
                    c = ')'
            else:
                c = '√('
            # incrementa la cadena con c
            cadena = self.modcad(cadena, str(c))
        elif c == 'p':  # p
            # Debe enviar al valor p sólo si no estamos ahí
            if (self.dondestoy != 'p'):
                self.calculadora('SETP', cadena, p, q)
                return
        elif c == 'q':  # q
            # Debe enviar al valor q sólo si no estamos ahí
            if (self.dondestoy != 'q'):
                self.calculadora('SETQ', cadena, p, q)
                return

        if (self.dondestoy == 'p'):
            p = cadena
        if (self.dondestoy == 'q'):
            q = cadena
        # if (q==''):
        #     q = '1'
        self.operacion(p, q)

    def calculadora(self, estado, cadena='', p='', q=''):
        if (estado == 'RESULTADO'):
            self.calcelUpdate('Nuevo resultado')
            self.porcion = ''
            self.memvel = 0  #Memoria de la volicidad actual
            if self.vel > 0:
                self.memvel = self.vel
            self.vel = -1  # Stop timer
            self.contador = -1  # Reset timer
            if self.sendToDisplay > 0:
                self.arduino.write('N')  # RESET DYSPLAY
                time.sleep(1)
            if (self.dondestoy == 'p'):
                p = cadena
            if (self.dondestoy == 'q'):
                q = cadena
            if p == '':
                p = '0'
            if (q == ''):
                q = '1'
            rcadena = p[::-1]
            if '(' in rcadena:
                if ')' in rcadena:
                    ax = rcadena.index('(')
                    cx = rcadena.index(')')
                    if ax < cx:
                        p = p + ')'
                else:
                    p = p + ')'
            rcadena = q[::-1]
            if '(' in rcadena:
                if ')' in rcadena:
                    ax = rcadena.index('(')
                    cx = rcadena.index(')')
                    if ax < cx:
                        q = q + ')'
                else:
                    q = q + ')'
            self.resultado(p, q)

        if (estado == 'REINICIAR'):
            self.calcelUpdate('Reiniciar')
            self.resultadoNormal = ''
            self.resultadoAduino = ''
            self.vel = -1  # Stop timer
            self.contador = -1  # Reset timer
            self.operacion(p='', q=1)
            self.resultastr = ''
            self.resulta.set(self.resultastr)
            self.dondestoy = 'p'
            self.labelp.config(bg="#fd0")
            self.labelq.config(bg="#eee")
            if self.sendToDisplay > 0:
                self.arduino.write('N')  # RESET DYSPLAY
                time.sleep(1)
            # self.calculadora()
        if (estado == 'SALIR'):
            self.calcelUpdate()
            logging.info("INFO\tSalir del programa")
            time.sleep(1)
            self.vel = -1  # Stop timer
            self.master.quit()
            # return
        if (estado == 'SETP'):
            q = cadena
            if '(' in q and ')' not in q:
                q = q + ')'
            if q == '0' or q == '':
                self.divisorstr = str('1')
                self.divisor.set(self.divisorstr)
                self.labelq.config(fg="#aaa")
            self.dondestoy = 'p'
            self.labelp.config(bg="#fd0")
            self.labelq.config(bg="#eee")
            # self.calculadora(p,p,q,dondestoy)
        if (estado == 'SETQ'):
            p = cadena
            if '(' in p and ')' not in p:
                p = p + ')'
            if q == '1':
                self.divisorstr = str('')
                self.divisor.set(self.divisorstr)
                self.labelq.config(fg="#aaa")
            self.dondestoy = 'q'
            self.labelp.config(bg="#eee")
            self.labelq.config(bg="#fd0")
            # self.calculadora(q,p,q,dondestoy)

    def maxlen(self, p, q):
        maxlen = len(str(p))
        if (len(str(q)) > maxlen):
            maxlen = len(str(q))
        lp = len(str(p))
        lq = len(str(q))
        return maxlen, lp, lq

    def operacion(self, p='', q=1):
        ml, lp, lq = self.maxlen(p, q)
        self.dividendostr = str(p)
        self.dividendo.set(self.dividendostr)
        self.divisorstr = str(q)
        self.divisor.set(self.divisorstr)

        # Color gris en divisor cuando es 1
        if self.divisorstr != "1":
            self.labelq.config(fg="#000")
        else:
            self.labelq.config(fg="#aaa")

    def resultado(self, p, q):
        self.calcelUpdate()
        ml, lp, lq = self.maxlen(p, q)
        self.dividendostr = str(p)
        self.dividendo.set(self.dividendostr)
        self.divisorstr = str(q)
        self.divisor.set(self.divisorstr)

        # Color gris en divisor cuando es 1
        if self.divisorstr != "1":
            self.labelq.config(fg="#000")
        else:
            self.labelq.config(fg="#aaa")

        ################################################
        # Calcula p/q en la presición definida
        equa = '(' + p + ')/(' + q + ')'
        res = self.nsp.eval(equa)

        # RESULTADO COMO CADENA
        nres = ''
        sres = str(res)
        if sres == 'ERROR':
            self.resultastr = sres
            self.resulta.set(self.resultastr)
            logging.info("ERROR\t" + equa)
            return
        # Set start envio Arduino
        self.resultadoNormal = sres
        self.resultadoAduino = self.filtrar(sres)
        self.contador = -1
        self.vel = self.memvel
        logging.info("OK\t" + equa)
        # Inicia envío a display arduino
        self.onUpdate()

    def calcelUpdate(self, quien=''):
        if self.playwaves > 0:
            mu.newfreq = 0
        if self._job is not None:
            if quien != '':
                logging.info("CANCEL\t" + quien)
            self.master.after_cancel(self._job)
            self._job = None

    def onUpdate(self):
        self.calcelUpdate()
        # Actualiza el caracter enviado, la posición y el estado actual (pausa/play)
        self.contador = self.contador + 1
        inicio = self.contador - self.porcionlen
        if self.contador > self.maxprec:
            self.porcion = ''
            self.contador = 0
            self.resultado(self.dividendostr, self.divisorstr)
            if self.playwaves > 0:
                mu.newfreq = 0
            return
        if inicio < 0:
            inicio = 0
        if self.contador > len(self.resultadoAduino) - 1:
            enviar = '0'
        else:
            enviar = self.resultadoAduino[self.contador]
        self.porcion = self.porcion + enviar
        if len(self.porcion) > self.porcionlen - 1:
            self.porcion = self.porcion[-self.porcionlen:]

        if self.debuguear > 0:
            salida = u"Resultado: " + self.resultadoNormal[0:self.porcionlen]
            salida = salida + u"\nVelocidad: " + str(
                self.velist[self.vel]) + " ms"
            tiempofaltante = round(
                self.velist[self.vel] *
                (len(self.resultadoAduino) - self.contador) / 1000)
            m, s = divmod(tiempofaltante, 60)
            h, m = divmod(m, 60)
            salida = salida + u"\nTiempo restante: " + str("%d:%02d:%02d" %
                                                           (h, m, s)) + " hms"
            salida = salida + u"\nPosición: " + str(
                self.contador) + " / " + str(len(self.resultadoAduino))
            salida = salida + u"\nDígito: " + enviar
            salida = salida + u"\nPorción: " + self.porcion.rjust(
                self.porcionlen, ' ').replace(' ', '  ')
            self.resultastr = salida
            self.resulta.set(self.resultastr)

        if self.playwaves > 0:
            self.stream.start_stream()
            try:
                nx = int(enviar)
            except ValueError:
                nx = -1
                pass
            if nx > 0:
                nx = nx - 1
            elif nx == 0:
                nx = -1
            if nx < 0:
                mu.newfreq = 0
            else:
                mu.newfreq = mu.listaFreq[nx]

        # ENVIO A DISPLAY
        if self.sendToDisplay > 0:
            self.arduino.write(
                enviar
            )  # Envia digito actual a DISPLAY, la pausa la genera el unUpdate mismo
        # DEBUG EN CONSOLA
        if self.debuguear > 1:
            print(current_iso8601(), self.contador, self.vel,
                  self.velist[self.vel], enviar)
        # schedule timer para ayutollamarse cada segundo
        if self.vel >= 0:
            self._job = self.master.after(self.velist[self.vel], self.onUpdate)

        # Versión de prueba !!!
        if self.playsounds > 0 and self.char2wav(enviar) != '':
            corto = ''
            if self.velist[self.vel] < 300:
                corto = '_'
            winsound.PlaySound('wav/' + self.char2wav(enviar) + corto + '.wav',
                               winsound.SND_FILENAME | winsound.SND_ASYNC)

    def char2wav(self, c):
        r = {
            'A': '1',
            'B': '2',
            'C': '3',
            'D': '4',
            'E': '5',
            'G': '7',
            'H': '8',
            'I': '9',
            'J': '0',
            '-': '0'
        }
        if c in r.keys():
            c = r[c]
        n = {
            # '1':'c1', '2':'d1', '3':'e1', '4':'f1', '5':'', '6':'g1', '7':'a1', '8':'b1', '9':'c2', '0':'' # Mayor, Silencios: 0, 5
            '1': 'c1',
            '2': 'd1',
            '3': 'd1s',
            '4': 'e1',
            '5': 'f1',
            '6': 'g1',
            '7': 'a1',
            '8': 'b1',
            '9': 'c2',
            '0': ''  # Mayor/Menor, Silencio: 0
        }
        return n[c]
Exemple #43
0
class MainWindow(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.parent = parent
        menubar = MenuBar(self)
        self.area = self.create_area()
        self.button_start, self.scale_circle = self.create_controls()
        self.libelle = Label(text="Serious Game",
                             font="Helvetica 14 bold",
                             bg="white",
                             fg="red")
        menubar.pack()
        self.area.pack()
        self.libelle.pack(pady=3)

        self.x, self.y = 100, 100
        self.circle_bb = 100
        self.circle = None
        self.animation_id = None

    def create_area(self):
        canvas = ScrolledCanvas(self,
                                relief="solid",
                                scrollregion=(-600, -600, 600, 600),
                                bd=3)
        return canvas

    def create_controls(self):
        canvas = self.area.get_canvas()
        start = Button(self, text="Start", command=self.start)
        scale = Scale(self,
                      length=250,
                      orient="horizontal",
                      label='Rayon :',
                      troughcolor='dark grey',
                      sliderlength=20,
                      showvalue=0,
                      from_=0,
                      to=100,
                      tickinterval=25,
                      command=self.update_circle)
        scale.set(50)
        canvas.create_window(50, 200, window=start)
        canvas.create_window(250, 200, window=scale)
        return start, scale

    def create_circle(self):
        canvas = self.area.get_canvas()
        if self.circle != None:
            canvas.delete(self.circle)
        self.circle = canvas.create_oval(self.x,
                                         self.y,
                                         self.x + self.circle_bb,
                                         self.y + self.circle_bb,
                                         fill='yellow',
                                         outline='black')
        return self.circle

    def delete_circle(self):
        if self.circle != None:
            canvas = self.area.get_canvas()
            canvas.delete(self.circle)

    def update_circle(self, size):
        canvas = self.area.get_canvas()
        canvas.delete(self.circle)
        self.circle_bb = 2 * int(size)
        self.circle = self.create_circle()

    def animation(self):
        self.x += randrange(-60, 61)
        self.y += randrange(-60, 61)
        canvas = self.area.get_canvas()
        canvas.coords(self.circle, self.x, self.y, self.x + self.circle_bb,
                      self.y + self.circle_bb)
        self.libelle.config(text='Cherchez en %s %s' % (self.x, self.y))
        self.animation_id = self.after(250, self.animation)

    def stop(self):
        self.after_cancel(self.animation_id)
        self.button_start.configure(text="Start", command=self.start)

    def start(self):
        self.button_start.configure(text="Stop", command=self.stop)
        self.animation()

    def stop(self):
        self.parent.destroy()
Exemple #44
0
class Minesweeper:

    def __init__(self,master):
   
        self.tile_plain = PhotoImage(file = "images/tile_plain.gif")
        self.tile_clicked = PhotoImage(file = "images/tile_clicked.gif")
        self.tile_mine = PhotoImage(file = "images/tile_mine.gif")
        self.tile_flag = PhotoImage(file = "images/tile_flag.gif")
        self.tile_wrong = PhotoImage(file = "images/tile_wrong.gif")
        self.tile_no = []
        for x in range(1, 9):
            self.tile_no.append(PhotoImage(file = "images/tile_"+str(x)+".gif"))

        frame = Frame(master)
        frame.pack()

        self.label1 = Label(frame, text="Minesweeper")
        self.label1.grid(row = 0, column = 0, columnspan = 10)

        self.flags = 0
        self.correct_flags = 0
        self.clicked = 0

        # buttons
        self.buttons = dict({})
        self.mines = 0
        x_coord = 1
        y_coord = 0
        for x in range(0, 100):
            mine = 0
            
            gfx = self.tile_plain
          
            if random.uniform(0.0, 1.0) < 0.1:
                mine = 1
                self.mines += 1
            # 0 = Button widget
            # 1 = if a mine y/n (1/0)
            # 2 = state (0 = unclicked, 1 = clicked, 2 = flagged)
            # 3 = button id
            # 4 = [x, y] coordinates in the grid
            # 5 = nearby mines, 0 by default, calculated after placement in grid
            self.buttons[x] = [ Button(frame, image = gfx),
                                mine,
                                0,
                                x,
                                [x_coord, y_coord],
                                0 ]
            self.buttons[x][0].bind('<Button-1>', self.lclicked_wrapper(x))
            self.buttons[x][0].bind('<Button-3>', self.rclicked_wrapper(x))

            y_coord += 1
            if y_coord == 10:
                y_coord = 0
                x_coord += 1
        
        # lay buttons in grid
        for key in self.buttons:
            self.buttons[key][0].grid( row = self.buttons[key][4][0], column = self.buttons[key][4][1] )

        # find nearby mines and display number on tile
        for key in self.buttons:
            nearby_mines = 0
            if self.check_for_mines(key-9):
                nearby_mines += 1
            if self.check_for_mines(key-10):
                nearby_mines += 1
            if self.check_for_mines(key-11):
                nearby_mines += 1
            if self.check_for_mines(key-1):
                nearby_mines += 1
            if self.check_for_mines(key+1):
                nearby_mines += 1
            if self.check_for_mines(key+9):
                nearby_mines += 1
            if self.check_for_mines(key+10):
                nearby_mines += 1
            if self.check_for_mines(key+11):
                nearby_mines += 1
            
            self.buttons[key][5] = nearby_mines
            
        self.label2 = Label(frame, text = "Mines: "+str(self.mines))
        self.label2.grid(row = 11, column = 0, columnspan = 5)

        self.label3 = Label(frame, text = "Flags: "+str(self.flags))
        self.label3.grid(row = 11, column = 4, columnspan = 5)


    def check_for_mines(self, key):
        try:
            if self.buttons[key][1] == 1:
                return True
        except KeyError:
            pass

    def lclicked_wrapper(self, x):
        return lambda Button: self.lclicked(self.buttons[x])

    def rclicked_wrapper(self, x):
        return lambda Button: self.rclicked(self.buttons[x])

    def lclicked(self, button_data):
        if button_data[1] == 1: #if a mine
            # show all mines and check for flags
            for key in self.buttons:
                if self.buttons[key][1] != 1 and self.buttons[key][2] == 2:
                    self.buttons[key][0].config(image = self.tile_wrong)
                if self.buttons[key][1] == 1 and self.buttons[key][2] != 2:
                    self.buttons[key][0].config(image = self.tile_mine)
            # end game
            self.gameover()
        else:
            #change image
            if button_data[5] == 0:
                button_data[0].config(image = self.tile_clicked)
                self.clear_empty_tiles(button_data[3])
            else:
                button_data[0].config(image = self.tile_no[button_data[5]-1])
            # if not already set as clicked, change state and count
            if button_data[2] != 1:
                button_data[2] = 1
                self.clicked += 1
            if self.clicked == 100 - self.mines:
                self.victory()

    def rclicked(self, button_data):
        # if not clicked
        if button_data[2] == 0:
            button_data[0].config(image = self.tile_flag)
            button_data[2] = 2
            button_data[0].unbind('<Button-1>')
            # if a mine
            if button_data[1] == 1:
                self.correct_flags += 1
            self.flags += 1
            self.update_flags()
        # if flagged, unflag
        elif button_data[2] == 2:
            button_data[0].config(image = self.tile_plain)
            button_data[2] = 0
            button_data[0].bind('<Button-1>', self.lclicked_wrapper(button_data[3]))
            # if a mine
            if button_data[1] == 1:
                self.correct_flags -= 1
            self.flags -= 1
            self.update_flags()

    def check_tile(self, key, queue):
        try:
            if self.buttons[key][2] == 0:
                if self.buttons[key][5] == 0:
                    self.buttons[key][0].config(image = self.tile_clicked)
                    queue.append(key)
                else:
                    self.buttons[key][0].config(image = self.tile_no[self.buttons[key][5]-1])
                self.buttons[key][2] = 1
                self.clicked += 1
        except KeyError:
            pass

    def clear_empty_tiles(self, main_key):
        queue = deque([main_key])

        while len(queue) != 0:
            key = queue.popleft()
            self.check_tile(key-9, queue)      #top right
            self.check_tile(key-10, queue)     #top middle
            self.check_tile(key-11, queue)     #top left
            self.check_tile(key-1, queue)      #left
            self.check_tile(key+1, queue)      #right
            self.check_tile(key+9, queue)      #bottom right
            self.check_tile(key+10, queue)     #bottom middle
            self.check_tile(key+11, queue)     #bottom left
    
    def gameover(self):
        tkMessageBox.showinfo("Game Over", "You Lose!")
        global root
        root.destroy()

    def victory(self):
        tkMessageBox.showinfo("Game Over", "You Win!")
        global root
        root.destroy()

    def update_flags(self):
        self.label3.config(text = "Flags: "+str(self.flags))
Exemple #45
0
class TrainingSetEditor(object):
    """ Class responsible for rendering editor's UI. """

    _crop_area = CropArea(65, 140, 180, 466)
    _feature_labels = [('Snow', 'S'), ('Rain', 'R'), ('Storm', 'T'),
                       ('Strong wind', 'W'), ('Clouds', 'C')]

    def __init__(self, size, data_store):
        """
        Args:
            size (EditorSize): class representing internal sizes of the editor.
            data_store (TrainingDataStore): class providing files for processing.
        """
        assert type(
            size) is EditorSize, 'size: passed object of incorrect type'
        assert type(
            data_store
        ) is TrainingDataStore, 'data_store: passed object of incorrect type'

        self._size = size
        self._data_store = data_store

    def _setup(self, size):
        """ Method which does the initial setup of the UI. """
        self._root_window = Tk()
        self._root_window.title("Training set editor")
        self._root_window.resizable(width=False, height=False)

        self._setup_progress(size)
        self._setup_image_label(size)
        self._setup_features(size)
        self._setup_next_button(size)
        self._current_training_input = self._data_store.get_training_input(
            self._data_store.current_file_index)

    def _setup_progress(self, size):
        """ Method which does the initial setup of progress labels. """
        label_1 = Label(self._root_window, text='Processing image')
        label_1.grid(row=0, column=0)

        self._current_image_index_text = Text(self._root_window,
                                              height=1,
                                              width=6)
        self._current_image_index_text.insert(
            END, str(self._data_store.current_file_index))
        self._current_image_index_text.grid(row=0, column=1)

        label_3 = Label(self._root_window, text='out of')
        label_3.grid(row=0, column=2)

        self._total_images_count_label = Label(
            self._root_window, text=str(self._data_store.total_files_count))
        self._total_images_count_label.grid(row=0, column=3)

    def _setup_image_label(self, size):
        """ Method which does the initial setup of meteorogram preview image. """
        self._label = Label(self._root_window, width=size.content_width)
        self._label.grid(row=1, column=0, columnspan=5, sticky=(N, W, E, S))

    def _setup_features(self, size):
        """ Method which does the initial setup of features checkboxes. """
        self._buttons = {}
        for index in range(len(self._feature_labels)):
            label = self._feature_labels[index][0]
            value = self._feature_labels[index][1]
            checkbox = Checkbutton(self._root_window,
                                   text=label,
                                   onvalue=value,
                                   offvalue='')
            checkbox.grid(row=2, column=index)

            self._root_window.bind(value.lower(), self._on_feature_toggled)
            self._buttons[value] = checkbox

    def _setup_next_button(self, size):
        """ Method which does the initial setup of the next button. """
        self._next_button = Button(self._root_window,
                                   text='NEXT',
                                   command=self._on_next_button_click)
        self._next_button.grid(row=3,
                               column=0,
                               columnspan=5,
                               sticky=(N, W, E, S))
        self._root_window.bind('<Return>', self._on_next_button_click)

    def _update_feature_buttons_binding(self):
        """ Method which rebinds keyboard shortcuts for the next meteorogram image. """
        self._buttons['S'].config(
            variable=self._current_training_input.features.snow)
        self._buttons['R'].config(
            variable=self._current_training_input.features.rain)
        self._buttons['T'].config(
            variable=self._current_training_input.features.storm)
        self._buttons['W'].config(
            variable=self._current_training_input.features.strong_wind)
        self._buttons['C'].config(
            variable=self._current_training_input.features.clouds)

        for feature_sign in self._current_training_input.features.label:
            if feature_sign in self._buttons:
                self._buttons[feature_sign].select()

    def _update_progess_labels(self):
        """ Method progress labels when a meteorogram was processed. """
        self._current_image_index_text.delete(1.0, END)
        self._current_image_index_text.insert(
            END, str(self._data_store.current_file_index))
        self._total_images_count_label.config(
            text=str(self._data_store.total_files_count))

    def _on_feature_toggled(self, event):
        """ Method called when feature checkbox was toggled. """
        self._buttons[event.char.upper()].toggle()

    def _on_next_button_click(self, event=None):
        """ Method called when next button was activated. """
        self._data_store.update_training_input(self._current_training_input)

        if self._data_store.current_file_index % 50 == 0:
            self._data_store.dump_index()

        try:
            next_index = self._get_next_accepted_item(
                builder_blueprint.accept_fn_index['clouds-present'])
            self._current_training_input = self._data_store.get_training_input(
                next_index)
            self._show_image(self._current_training_input)
            self._update_progess_labels()
        except ValueError:
            self._update_progess_labels()

    def _get_next_item_index(self):
        """ Method returns the index of next meteorogram to process """
        inputString = self._current_image_index_text.get(1.0, END).encode(
            'ascii', 'ignore')
        newIndex = int(re.sub('[^0-9]', '', inputString))
        return newIndex if newIndex != self._data_store.current_file_index else newIndex + 1

    def _get_next_accepted_item(self, accept_fn):
        index = self._get_next_item_index()
        while True:
            input = self._data_store.get_training_input(index)
            if accept_fn(input.features.label):
                return index
            else:
                index += 1

    def _show_image(self, training_input):
        """ Method displays the next meteorogram image. """
        self._current_preview = TrainingImagePreview(training_input.path,
                                                     self._crop_area)
        self._current_preview.save(self._data_store.preview_path)
        self._update_feature_buttons_binding()

        img = ImageTk.PhotoImage(Image.open(self._data_store.preview_path))
        self._label.configure(image=img)
        self._label.image = img

    def activate(self):
        """ Method displays editor's window on the screen. """
        self._setup(self._size)
        self._show_image(self._current_training_input)
        self._root_window.mainloop()
Exemple #46
0
class Gui(Frame, threading.Thread):
  
    def __init__(self, parent):
        threading.Thread.__init__(self)
        Frame.__init__(self, parent)   
        self.parent = parent
        self.closeRequest = False
        
        self.initUI()
        self.start()
        
    
    def initUI(self):
        self.parent.title("Crazyflie Client")

        Label(self, text="Pitch").place(x=5, y=5)
        self.label_pitch = Label(self, text="0.00")
        self.label_pitch.place(x=60, y=5)
        
        Label(self, text="Roll").place(x=5, y=25)
        self.label_roll = Label(self, text="0.00")
        self.label_roll.place(x=60, y=25)
        
        Label(self, text="Yaw").place(x=5, y=50)
        self.label_yaw = Label(self, text="0.00")
        self.label_yaw.place(x=60, y=50)
        
        Label(self, text="Throttle").place(x=5, y=70)
        self.label_thrust = Label(self, text="0.00")
        self.label_thrust.place(x=60, y=70)
        
        self.canvas1 = Canvas(self, bg="#ddd", width=150, height=150)
        self.canvas1.place(x=395, y=25)
        
        self.canvas2 = Canvas(self, bg="#eee", width=340, height=280)
        self.canvas2.place(x=300, y=200)
        
        self.pack(fill=BOTH, expand=1)
        
    def onClose(self):
        self.closeRequest = True
        
    def drawCanvas1(self, status):
        self.canvas1.delete("all")
        
        max = 30.
        x = (status.roll / max) * 75 + 76
        y = (status.pitch / max) * 75 + 76
        
        w0 = 2
        w10 = 75 * 1 / 3.
        w20 = 75 * 2 / 3. 
        w30 = 75 * 3 / 3.
        self.canvas1.create_line(76, 0, 76, 150, fill="#bbb")
        self.canvas1.create_line(0, 76, 150, 76, fill="#bbb")
        self.canvas1.create_oval(76 - w0, 76 - w0, 76 + w0, 76 + w0, outline="#bbb")
        self.canvas1.create_oval(76 - w10, 76 - w10, 76 + w10, 76 + w10, outline="#bbb")
        self.canvas1.create_oval(76 - w20, 76 - w20, 76 + w20, 76 + w20, outline="#bbb")
        self.canvas1.create_oval(76 - w30, 76 - w30, 76 + w30, 76 + w30, outline="#bbb")
        
        self.canvas1.create_oval(x - 4, y - 4, x + 4, y + 4, fill="#000")
        
    
    def drawCanvas2(self, status):
        self.canvas2.delete("all")
        
        w = 40
        w2 = 80
        self.canvas2.create_rectangle(0 * w2, 0, w + 0 * w2, 200, outline="#aaa")
        self.canvas2.create_rectangle(1 * w2, 0, w + 1 * w2, 200, outline="#aaa")
        self.canvas2.create_rectangle(2 * w2, 0, w + 2 * w2, 200, outline="#aaa")
        self.canvas2.create_rectangle(3 * w2, 0, w + 3 * w2, 200, outline="#aaa")
        
        pixel_M1 = (status.motor_1 / 60000.) * 200
        pixel_M2 = (status.motor_2 / 60000.) * 200
        pixel_M3 = (status.motor_3 / 60000.) * 200
        pixel_M4 = (status.motor_4 / 60000.) * 200
        
        self.canvas2.create_rectangle(0 * w2, 200 - pixel_M1, w + 0 * w2, 200, fill="#0f0", outline="#0f0")
        self.canvas2.create_rectangle(1 * w2, 200 - pixel_M2, w + 1 * w2, 200, fill="#0f0", outline="#0f0")
        self.canvas2.create_rectangle(2 * w2, 200 - pixel_M3, w + 2 * w2, 200, fill="#0f0", outline="#0f0")
        self.canvas2.create_rectangle(3 * w2, 200 - pixel_M4, w + 3 * w2, 200, fill="#0f0", outline="#0f0")
    
        self.canvas2.create_rectangle(75, 230, 275, 270, outline="#aaa")
        pixel_bat = (status.bat / 4.) * 200
        self.canvas2.create_rectangle(75, 230, 75 + pixel_bat, 270, fill="#0f0", outline="#0f0")

    
    def run(self):
        while self.closeRequest == False:
            fc = flight.getFlightController()
            
            self.label_pitch.config(text="%2.2f" % fc.pitch)
            self.label_roll.config(text="%2.2f" % fc.roll)
            self.label_yaw.config(text="%2.2f" % fc.yawrate)
            self.label_thrust.config(text="%2.2f" % fc.throttle)
            
            self.drawCanvas1(flight.getCFStatus())
            self.drawCanvas2(flight.getCFStatus())
            
            time.sleep(0.05)
            
        self.quit()
Exemple #47
0
class Input:
    """
	(TO DO)
	"""

    #================================================================
    def __init__(self, master, t1="x", t2="", name=""):
        """
		(TO DO)
		"""

        if name == "":
            self.label1 = Label(master, text=t1)
            self.label2 = Label(master, text=t2)
            self.tBox = Entry(master)

        else:
            self.label1 = Label(master, text=t1, name=("lb1_" + name))
            self.label2 = Label(master, text=t2, name=("lb2_" + name))
            self.tBox = Entry(master, name=("tbox_" + name))

    #================================================================
    def __call__(self, cFactor=1.):
        """
		(TO DO)
		"""
        return self.get(cFactor)

    #===============================================================
    def get(self, cFactor=1.):
        """
		(TO DO)
		"""

        tmp = float(self.tBox.get())
        return tmp * cFactor

    #================================================================
    def set(self, value):
        """
		(TO DO)
		"""
        self.tBox.delete(0, END)
        self.tBox.insert(0, value)

    #================================================================
    def enable(self):
        """
		(TO DO)
		"""
        self.label1.config(state=NORMAL)
        self.label2.config(state=NORMAL)
        self.tBox.config(state=NORMAL)

    #================================================================
    def disable(self):
        """
		(TO DO)
		"""
        self.label1.config(state=DISABLED)
        self.label2.config(state=DISABLED)
        self.tBox.config(state=DISABLED)
    tkMessageBox.showinfo('Hello', message='We are the Medical Coding Team!')
    return


app = Tk()
app.title('My Gui')
app.geometry('1000x700+600+600')

label1 = Label(app,
               text='- No day should pass without something being done :) -',
               bg='maroon',
               fg='white',
               relief=RAISED,
               height=2)
buttonfont = ('georgia', 14, 'bold')
label1.config(font=buttonfont)
label1.pack(side='top', fill=BOTH)

button1 = Button(app,
                 text='By   Date',
                 bg='white',
                 fg='red',
                 width=20,
                 command=dateDis)
buttonfont = ('georgia', 12, 'bold')
button1.config(font=buttonfont)
button1.pack(side='top', padx=35, pady=5)

button1 = Button(app,
                 text='Logout',
                 bg='maroon',
Exemple #49
0
class GUI(Thread):
    def __init__(self, master, mw, mh):

        # Basic settings of display
        self.root = master
        self.w, self.h = mw, mh
        self.root.overrideredirect(1)
        self.root.geometry("%dx%d+0+0" % (self.w, self.h))
        self.root.configure(background='black')
        master.title("DISPLAY")

        self.frameLeftTop = Frame(master,
                                  bg="black",
                                  width=self.w / 6,
                                  height=self.h / 6)
        self.frameMiddleTop = Frame(master,
                                    bg="black",
                                    width=self.w * 4 / 6,
                                    height=self.h / 6)
        self.frameRightTop = Frame(master,
                                   bg="black",
                                   width=self.w / 6,
                                   height=self.h / 6)
        self.frameLeftMiddle = Frame(master,
                                     bg="black",
                                     width=self.w / 6,
                                     height=self.h * 4 / 6)
        self.frameMiddleMiddle = Frame(master,
                                       bg="black",
                                       width=self.w * 4 / 6,
                                       height=self.h * 4 / 6)
        self.frameRightMiddle = Frame(master,
                                      bg="black",
                                      width=self.w / 6,
                                      height=self.h * 4 / 6)
        self.frameBottomLeft = Frame(master,
                                     bg="black",
                                     width=self.w / 6,
                                     height=self.h / 6)
        self.frameBottomMiddle = Frame(master,
                                       bg="black",
                                       width=self.w * 4 / 6,
                                       height=self.h / 6)
        self.frameBottomRight = Frame(master,
                                      bg="black",
                                      width=self.w / 6,
                                      height=self.h / 6)

        self.frameLeftTop.grid(row=0, column=0)
        self.frameMiddleTop.grid(row=0, column=1)
        self.frameRightTop.grid(row=0, column=2)
        self.frameLeftMiddle.grid(row=1, column=0)
        self.frameMiddleMiddle.grid(row=1, column=1)
        self.frameRightMiddle.grid(row=1, column=2)
        self.frameBottomLeft.grid(row=2, column=0)
        self.frameBottomMiddle.grid(row=2, column=1)
        self.frameBottomRight.grid(row=2, column=2)

        # Initialisation of components on display with default options
        self.mainMessage = Label(self.frameMiddleTop,
                                 background="black",
                                 fg="white",
                                 font=("Helvetica", (self.w / self.h) * 50))

        self.time = Label(self.frameBottomLeft,
                          background="black",
                          fg="white",
                          font=("Helvetica", (self.w / self.h) * 50))

        self.date = Label(self.frameBottomMiddle,
                          background="black",
                          fg="white",
                          font=("Helvetica", (self.w / self.h) * 50))

        self.weatherTemp = Label(self.frameLeftTop,
                                 background="black",
                                 fg="white",
                                 font=("Helvetica", (self.w / self.h) * 50))
        """
        self.location = Label(frameLeftTop,
                              background="black",
                              fg="white",
                              font=("Helvetica", 40))
        """

        self.weatherImage = Label(self.frameLeftMiddle)

        self.updateTime = Label(self.frameRightTop,
                                background="black",
                                fg="white",
                                font=("Helvetica", (self.w / self.h) * 10))

        # Start of the tread (when object is initialized)
        Thread.__init__(self)
        self.start()

    # Overwriting the run method (fired when start() is called)
    def run(self):

        # Keep running while the program is active
        print("GUI IS RUNNING...")
        loop_active = True
        while loop_active:

            startTime = time.time()

            # re-call channel1 to get updated information
            pub.dispatch("channel1")

            # config all components on display and show the components with new content from channel1
            self.mainMessage.config(text=sub1.data.mainMessage)
            self.mainMessage.place(x=(self.w * 4 / 6) / 2,
                                   y=(self.h / 6) / 2,
                                   anchor="center")

            self.time.config(text=sub1.data.time)
            self.time.place(x=(self.w / 6) / 2,
                            y=(self.h / 6) / 2,
                            anchor="center")

            self.date.config(text=sub1.data.date)
            self.date.place(x=(self.w * 4 / 6) / 2,
                            y=(self.h / 6) / 2,
                            anchor="center")

            if (sub1.data.weather.currentTemp != None):
                self.weatherTemp.config(text=sub1.data.weather.currentTemp +
                                        u'\N{DEGREE SIGN}' + "C")
                self.weatherTemp.grid(row=2)
            else:
                self.weatherTemp.config(text="Themperture Not Found!")
                self.weatherTemp.grid(row=2)
            """    
            if (sub1.data.weather.country != None or sub1.data.weather.location != None):
                self.location.config(text=sub1.data.weather.country+ " - " +sub1.data.weather.location)
                self.location.grid(row=3)
            else:
                self.location.config(text="Location Not Found!")
                self.location.grid(row=3)
            """

            if (sub1.data.weather.imageName != None):
                photo = PhotoImage(file=sub1.data.weather.imageName)
                self.weatherImage.config(image=photo,
                                         borderwidth=0,
                                         highlightthickness=0)
                self.weatherImage.grid(row=4)
            else:
                photo = PhotoImage(file="img/Danger.gif")
                self.weatherImage.config(image=photo,
                                         borderwidth=0,
                                         highlightthickness=0)
                self.weatherImage.grid(row=4)

            self.updateTime.config(text=str(time.time() - startTime))
            self.updateTime.grid(row=0, column=3)

            time.sleep(5)
Exemple #50
0
class App(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack(fill=BOTH, expand=True)

        url_lab = Label(frame,
                        text='URL:',
                        fg='green',
                        font=('Courier New', 16))
        url_lab.grid(row=0, column=0, sticky=N + E)

        self.url_text = Text(frame,
                             width=60,
                             height=3,
                             font=('Courier New', 12))
        self.url_text.grid(row=0, column=1)

        f5_lab = Label(frame,
                       text='F5 Big-Ip:',
                       fg='blue',
                       font=('Courier New', 14))
        f5_lab.grid(row=1, column=0, sticky=N)

        self.f5bigip = StringVar()
        self.f5bigipEntry = Entry(frame, textvariable=self.f5bigip)
        self.f5bigipEntry.config(font=('Courier New', 12))
        self.f5bigipEntry.config(width=60)
        self.f5bigipEntry.grid(row=1, column=1)

        self.testbtn = Button(frame, text='检测', font=('Courier New', 12))
        self.testbtn.config(width=25)
        self.testbtn.config(bg='LightSkyBlue')
        self.testbtn.grid(row=2, column=1, sticky=W)

        self.decodebtn = Button(frame,
                                text='解码F5 Big-Ip 值',
                                font=('Courier New', 12))
        self.decodebtn.config(width=25)
        self.decodebtn.config(bg='LightSkyBlue')
        self.decodebtn.grid(row=2, column=1, sticky=E)

        self.result_lab = Label(frame,
                                text='执行结果:',
                                fg='blue',
                                font=('Courier New', 14))
        self.result_lab.grid(row=3, column=0, sticky=N + E)

        scroll = Scrollbar(frame)
        scroll.grid(row=3, column=1, sticky=E + N + S)
        self.response = Text(frame,
                             width=58,
                             height=18,
                             font=('Courier New', 12))
        self.response.grid(row=3, column=1, sticky=W + S)
        self.response.config(yscrollcommand=scroll.set)
        scroll.config(command=self.response.yview)

        self.msg = StringVar()
        self.msg_lab = Label(frame,
                             textvariable=self.msg,
                             fg='blue',
                             font=('Courier New', 12))
        self.msg_lab.grid(row=4, column=0, columnspan=2, sticky=N + S + W + E)

        self.testbtn.bind('<Button-1>', self.check)
        self.decodebtn.bind('<Button-1>', self.decode_bigip2)

        self.url = ''
        self.pattern = re.compile('^(?:http|https)://(?:\w+\.)+.+')

        self.headers = {
            "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
        }

    def check(self, event):
        self.msg.set('')
        self.url = self.url_text.get(1.0, END).strip()
        chek_url = self.pattern.match(self.url)
        # print chek_url.group()
        if not chek_url:
            # print ('123')
            self.msg.set('请输入正确的(GET)URL!')
        else:
            try:
                self.msg.set('')
                self.f5bigip.set('')
                self.response.delete(1.0, END)
                response = get(self.url, headers=self.headers)
                headers = response.headers
                set_cookie = headers.get('Set-cookie', None)
                headers = '\n'.join(
                    [':'.join(item) for item in response.headers.iteritems()])
                # print headers

                if set_cookie:
                    bigip_value = self.getBigIPvalue(set_cookie)
                    if bigip_value:
                        self.f5bigip.set(bigip_value)
                        self.msg_lab.config(fg='red')
                        host = self.decode_bigip(bigip_value)
                        self.msg.set(
                            'F5 BIG-IP Cookie Remote Information Disclosure\n'
                            '存在信息泄露漏洞!\n'
                            '内网地址:' + host)

                    else:
                        self.msg_lab.config(fg='blue')
                        self.msg.set('不存在信息泄露漏洞!')
                else:
                    self.msg_lab.config(fg='blue')
                    self.msg.set('不存在信息泄露漏洞!')

                self.response.delete(1.0, END)
                self.response.insert(END, headers + '\n\n' + response.text)

            except:
                self.msg_lab.config(fg='red')
                self.msg.set('网络资源请求失败,请确保已经接入互联网和网址的有效性!')

    def getBigIPvalue(self, set_cookie):
        if set_cookie:
            lst = set_cookie.split(';')
            lst = [item.split('=') for item in lst]
            # print lst
            for key, value in lst:
                if re.search('BIGipServer.*?', key):
                    return value

        return ''

    def decode_bigip(self, bigip_value):
        if bigip_value:
            if re.match('\d+\.\d+\.\d+', bigip_value):
                host, port, end = bigip_value.split('.')
                host = [ord(i) for i in struct.pack("<I", int(host))]
                port = [ord(e) for e in struct.pack("<H", int(port))]
                host = '.'.join([str(i) for i in host])
                port = '0x%02X%02X' % (port[0], port[1])
                # print port
                port = str(int(port, 16))

                return ':'.join([host, port])
            else:
                showerror(
                    'Decode F5 Bigip Error',
                    'Bigip value is Not a valid value !\n (xxx.xxx.xx)(x代表数字) '
                )
                return ''

        return ''

    def decode_bigip2(self, event):
        bigip_value = self.f5bigip.get().strip()
        result = self.decode_bigip(bigip_value)
        if result:
            showinfo("Decode F5 Bigip ", "%s : %s" % (bigip_value, result))
        else:
            showerror(
                'Decode F5 Bigip Error',
                'Bigip value is Not a valid value !\n (xxx.xxx.xx)(x代表数字) ')
Exemple #51
0
class Go_Game():
    """This class provides an input field to enter the size of the grid
    of the go game and start a new go game."""
    def __init__(self):
        """Display a form to enter the size of the grid of the go game
        and start it

        Arguments:
            -

        Attributes updated by this function:
            self.grid_size
        """

        # Create screen to ask for game settings
        starting_screen = Tk()

        # Create an input field for the grid size of the go game
        # (also add a callback method to detect changes)
        Label(starting_screen, text='Grid Size').grid(row=0)
        sv_grid_size = StringVar()
        sv_grid_size.trace("w",
                           lambda name, index, mode, sv=sv_grid_size: self.
                           callback_grid_size())
        self.grid_size = Entry(starting_screen, textvariable=sv_grid_size)
        self.grid_size.grid(row=0, column=1)

        # Create an input field for the name of the first (black) player
        # (also add a callback method to detect changes)
        Label(starting_screen, text='Name Player 1 (Black)').grid(row=1)
        sv_player_1 = StringVar()
        sv_player_1.trace(
            "w",
            lambda name, index, mode, sv=sv_player_1: self.callback_player_1())
        self.player_1_name = Entry(starting_screen, textvariable=sv_player_1)
        self.player_1_name.grid(row=1, column=1)

        # Create an input field for the name of the second (white) player
        # (also add a callback method to detect changes)
        Label(starting_screen, text='Name Player 2 (White)').grid(row=3)
        sv_player_2 = StringVar()
        sv_player_2.trace(
            "w",
            lambda name, index, mode, sv=sv_player_2: self.callback_player_1())
        self.player_2_name = Entry(starting_screen, textvariable=sv_player_2)
        self.player_2_name.grid(row=3, column=1)

        # Add a button to start a new go game
        Button(starting_screen, text='Start',
               command=self.start_game).grid(row=4, column=1, sticky=W, pady=4)

        # Create a label for messages
        self.info_label = Label(starting_screen, text='')
        self.info_label.grid(row=5, columnspan=2)

        # Display the starting screen
        mainloop()

    def callback_grid_size(self):
        """Empty the info label
        """
        self.info_label.config(text='')

    def callback_player_1(self):
        """Empty the info label
        """
        self.info_label.config(text='')

    def callback_player_2(self):
        """Empty the info label
        """
        self.info_label.config(text='')

    def start_game(self):
        """Start a new go game with a given grid size."""

        # Read the entered grid size
        n = self.grid_size.get()

        # Check if an integer was entered
        if not n.isdigit() or not int(n) > 1:
            self.info_label.config(
                text='Please enter a grid size larger than 1!')
            return None

        # Read the player's names
        player_1 = self.player_1_name.get()
        player_2 = self.player_2_name.get()

        # Check wheter names were entered
        if not player_1 or not player_2:
            self.info_label.config(text='Please enter your names!')
            return None

        #start a the game
        if __name__ == '__main__':
            Controller(n, player_1, player_2)
class GUI:
    def __init__(self, master):
        self.master = master
        master.title("Naive Bayes Classifier")
        #set up vars for gui logic
        self.browse_text = StringVar()
        self.val_bins = master.register(self.validate_bins)
        self.isBin = False
        self.isBrowse = False
        self.isTest = ''
        self.isBrowse = ''
        self.isTrain = ''
        #buttons
        self.button_browse = Button(master,
                                    text='Browse',
                                    command=lambda: self.DisplayDir())
        self.button_build = Button(master,
                                   text="Build",
                                   command=lambda: self.build())
        self.button_classify = Button(master,
                                      text="Classify",
                                      command=lambda: self.classify())
        #labels
        self.label_directory_path = Label(master, text="Directory Path")
        self.label_bins = Label(master, text="Discretization Bins")
        self.label_error = Label(master, text="", fg='red')
        #entries
        self.entry_browse = Entry(master, width=50)
        self.entry_bins = Entry(master,
                                width=50,
                                validatecommand=(self.val_bins, "%P", "%d"),
                                validate='key')
        # LAYOUT
        self.button_browse.grid(row=1, column=4)
        self.entry_browse.grid(row=1, column=2, columnspan=2)
        self.label_directory_path.grid(row=1, column=1)

        self.label_bins.grid(row=2, column=1)
        self.entry_bins.grid(row=2, column=2)

        self.button_build.grid(row=3, column=1)
        self.button_classify.grid(row=3, column=2)
        self.label_error.grid(row=4, column=2)
        self.master.minsize(width=700, height=200)
        #control buttons

        self.button_build['state'] = 'disabled'
        self.button_classify['state'] = 'disabled'

        # #Logic
        self.modelBuilder = ''  # build the model
        self.modelTrainer = ModelTrainer.ModelTrainer(
        )  # use the train file and clean it
        self.modelTest = ModelTest.ModelTest()
        self.modelClassifier = ''  #classification

    def validate_bins(self, v, d):
        try:
            value = int(v)
            if value > 1:
                if self.isBrowse:
                    self.button_build['state'] = 'normal'
                return True
            else:
                self.isBin = False
                tkMessageBox.showinfo("Alert Message", "Invalid number")
                return False
        except:
            if d == '0' and v == '':
                self.entry_bins.delete(1, 'end')
                if len(self.entry_bins.get()) == 1:
                    self.button_build['state'] = 'disabled'
                    self.button_classify['state'] = 'disabled'
                    self.isBin = False
                return True
            tkMessageBox.showinfo("Alert Message", "Invalid number")
            return False

    def build(self):
        self.label_error.config(text="Begin building")
        self.modelBuilder = ModelBuilder.ModelBuilder(self.isStructure)
        self.modelTrainer = ModelTrainer.ModelTrainer(self.isTrain,
                                                      self.modelBuilder,
                                                      self.entry_bins.get())
        self.modelTrainer.readFile()
        maxbins = self.modelTrainer.getMaxbins()
        if maxbins < int(self.entry_bins.get()):
            tkMessageBox.showinfo("Alert Message", "Invalid number of bins")
        elif os.stat(self.isTest).st_size == 0 or os.stat(
                self.isTrain).st_size == 0 or os.stat(
                    self.isStructure).st_size == 0:
            tkMessageBox.showinfo("Alert Message", "One of the files is empty")
        else:
            self.modelTrainer.fillMissingValues()
            self.modelTrainer.discretization()
            tkMessageBox.showinfo(
                "Alert Message",
                "Building classifier using train-set is done!")
            self.button_classify['state'] = 'normal'
            self.label_error.config(text='')

    def classify(self):
        self.modelTest.setdata(self.isTest, self.modelBuilder,
                               self.entry_bins.get())
        self.modelTest.cleanData()
        self.modelClassifier = ModelClassifier.ModelClassifier(
            self.entry_browse.get(), self.modelTrainer.getData(),
            self.modelTest.getData(), self.modelBuilder, self.entry_bins.get())
        self.modelClassifier.buildNaiveDictionary()
        self.modelClassifier.classify()
        self.modelClassifier.writeOutput()
        tkMessageBox.showinfo(
            "Alert Message",
            "Done classifying. output is ready in : {}".format(
                self.entry_browse.get()))

    def DisplayDir(self):
        feedback = askdirectory()
        self.browse_text.set(feedback)
        self.entry_browse.config(state='normal')
        self.entry_browse.delete(0, 'end')
        self.entry_browse.insert(0, self.browse_text.get())
        self.entry_browse.config(state='readonly')
        self.isTest = os.path.join(self.browse_text.get(), "test.csv")
        self.isTrain = os.path.join(self.browse_text.get(), "train.csv")
        self.isStructure = os.path.join(self.browse_text.get(),
                                        "Structure.txt")

        self.texterror = ""
        if (os.path.exists(self.isTest) and os.path.exists(self.isTrain)
                and os.path.exists(self.isStructure)):
            if self.isBin:
                self.button_build['state'] = 'normal'
                self.button_classify['state'] = 'normal'
                self.label_error.config(text='folder content is valid !')

            else:
                self.texterror = "please fill bin text field"
                self.isBrowse = True

        else:
            if (not os.path.exists(self.isTrain)
                    # and not os.path.exists(self.isStructure)
                    and not os.path.exists(self.isTest)):
                self.texterror = "train.csv , structure.txt and test.csv were not found"

            elif (not os.path.exists(self.isTrain)):
                self.texterror = "train.csv was not found"
            elif (not os.path.exists(self.isStructure)):
                self.texterror = "Structure.txt was not found"
            elif (not os.path.exists(self.isTest)):
                self.texterror = "test.csv was not found"
            self.isBrowse = False

        self.label_error.config(text=self.texterror)
Exemple #53
0
class Gui:
    """
        Create Gui.
    """
    def __init__(self, width, height, labels_text):
        """
            Create main window with main settings.
            :param width: Window width.
            :param height: Window height.
            :param labels_text: language data set.
            :type width: Int
            :type height: Int
            :type labels_text: Configuration
        """
        # Get logger
        self.logger = logging.getLogger(__name__)

        # Define stop event for video loop threading
        self.stop_thread_event = threading.Event()

        self.take_snapshot = False
        self.take_snapshot_timestamp = datetime.now()

        # Init Picamera.
        self.cam = PiCamera()
        self.raw_capture = PiRGBArray(self.cam)
        # Define resolution V2 camera
        self.camera_resolution_maps = {
            's': (640, 480),
            'm': (1280, 720),
            'l': (1640, 922),
            'xl': (1640, 1232),
            'xxl': (3280, 2464)
        }

        # Create Windows and set attributes
        self.logger.info("Create windows apps.")
        self.window = Tk()

        # Define window title
        self.window.wm_title(labels_text['title'])

        # Get screen coordonate to center apps.
        x_axe = (self.window.winfo_screenwidth() / 2) - (width / 2)
        y_axe = (self.window.winfo_screenheight() / 2) - (height / 2)

        # Set screen position. (center)
        self.window.wm_geometry('%dx%d+%d+%d' % (width, height, x_axe, y_axe))

        # Close window event.
        self.window.wm_protocol("WM_DELETE_WINDOW", self._on_close())

        # Append widgets
        self.logger.info("Add widgets to main windows.")

        # Add Snapshot button
        btn_take_picture = Button(self.window,
                                  text=labels_text["buttons"]["take_pictures"],
                                  command=self._take_picture)
        btn_take_picture.pack(side="bottom", fill="both", padx=10, pady=10)

        # Create Video Stream panel
        self.panel_video_stream = Label(self.window)

        # get button size
        _, btn_h = self._get_widget_size(btn_take_picture)

        self.panel_video_stream.config(width=(width - 20),
                                       height=((height - btn_h) - 20))
        self.panel_video_stream.pack(side="top", fill="both", padx=10, pady=10)

        # Start camera handler.
        self._start_cam_handler()

    @staticmethod
    def _get_widget_size(widget, attr=None):
        """
        Return width height of widget
        :param widget: Widget object
        :param attr: Specific attribut.
        :return: Width and Height
        """
        if attr == "width":
            return widget.winfo_width()
        elif attr == "height":
            return widget.winfo_height()
        else:
            return widget.winfo_width(), widget.winfo_height()

    def _video_loop(self):
        """
          Run video in loop
        """

        self.logger.info("Start video loop.")

        # Define camera framerate
        # default: 30
        self.cam.framerate = 30

        # Define brightness
        # default: 50
        # self.cam.brightness = 50

        # Define contrast
        # self.cam.contrast = 0

        # Define Camera settings
        # self.cam.sharpness = 0

        # Define image effect
        # You can choose between none, negative, solarize, sketch, denoise, emboss, oilpaint, hatch, gpen,
        # pastel, watercolor, film, blur, saturation, coloswap, washedout, posterise, colorpoint, colorbalance, cartoon,
        # deinterlace1 and deinterlace2
        # default: none
        self.cam.image_effect = 'none'

        # Define white balance
        # You can choose between off, auto, sunlight, cloudy, shade, tungsten, fluorescent, incandescent, flash, horizon
        # default: auto
        self.cam.awb_mode = 'auto'

        # Define exposure mode
        # You can choose between off, auto, night, nightpreview, blacklight, spotlight, sports, snow, beach, verylong,
        # fixedfps, antishake, fireworks
        # default: auto
        self.cam.exposure_mode = 'off'
        self.cam.exposure_compensation = 0

        # Define camera saturation
        # default: 0
        self.cam.saturation = 0

        # Define sensitivity of the camera light
        # You can define value between 100 and 1600.
        # Lower iso speed imply less sensitivity
        # default: 400
        self.cam.iso = 800

        # Define expose camera method
        # You can choose between average, spot, backlit, matrix
        # default: average
        self.cam.meter_mode = 'average'

        # Rotate camera
        self.cam.rotation = 270

        # Set horizontal or vertical flip.
        # default: false
        self.cam.hflip = True
        # self.cam.vflip = False

        # Set zoom in camera input
        # default: (0.0, 0.0, 1.0, 1.0)
        self.cam.crop = (0.0, 0.0, 1.0, 1.0)

        self.cam.video_stabilization = True

        # Define camera resolution.
        # Max resolution is 2592*1944
        # default: 1280*720
        _cam_width = (self._get_widget_size(self.window, "width") - 20)
        _cam_height = (
            self._get_widget_size(self.window, "height") -
            self._get_widget_size(self.panel_video_stream, "height") - 40)

        # If cam resolution is smaller than small configuration mapper
        if _cam_height < self.camera_resolution_maps['s'][
                0] or _cam_height < self.camera_resolution_maps['s'][1]:
            _cam_width, _cam_height = self.camera_resolution_maps['s']

        self.logger.info("Init camera resolution (%s,%s)", _cam_width,
                         _cam_height)
        self.cam.resolution = (_cam_width, _cam_height)

        self.logger.debug("Run capture loop.")
        timer = 0

        for frame in self.cam.capture_continuous(self.raw_capture,
                                                 format='rgb',
                                                 use_video_port=True):

            # If stop event set break capture loop
            if not self.stop_thread_event.is_set():
                break

            if self.take_snapshot:

                # Reset timer if older than 5 seconds.
                if (self.take_snapshot_timestamp +
                        timedelta(seconds=6)) < datetime.now():
                    self.take_snapshot_timestamp = datetime.now()
                    timer = 0

                # run countdown
                if (self.take_snapshot_timestamp + timedelta(seconds=timer)
                    ) < datetime.now() and timer < 6:
                    self.cam.annotate_text_size = 50

                    if (5 - timer) <= 1:
                        self.cam.annotate_text = 'smile'
                    else:
                        self.cam.annotate_text = str(5 - timer)
                    timer += 1

                elif timer == 6:
                    # Reset annotate
                    self.cam.annotate_text = ''
                    timestamp = datetime.now().strftime('%s')
                    img_filename = os.path.join(
                        "/home/pi/Pictures/",
                        "picture-{}.jpg".format(timestamp))
                    self.cam.capture(img_filename,
                                     resize=self.camera_resolution_maps['xxl'])
                    self.logger.info("Picture saved in %s.", img_filename)
                    self.take_snapshot = False

            # Get image array and display
            img = frame.array
            img = PIL.Image.fromarray(img)
            img = ImageTk.PhotoImage(img)

            self.panel_video_stream.configure(image=img)
            self.panel_video_stream.image = img
            self.raw_capture.truncate(0)

        self.logger.info("Stop video loop.")
        self.cam.close()
        self.raw_capture.close()

    def _start_cam_handler(self):
        """
          Create Thread to video loop.
        """
        self.logger.debug("Start thread camera handler.")

        cam_thread = threading.Thread(target=self._video_loop)
        cam_thread.start()

    def _take_picture(self):
        """
            Take picture from video flux.
        """
        self.logger.debug("Take picture.")
        self.take_snapshot = True

    def run(self):
        """
            Start Gui apps.
        """
        self.logger.debug("Start main loop.")
        self.window.mainloop()

    def _on_close(self):
        """
          Close photobooth apps
        """
        self.logger.info("Stop photoobooth apps.")

        # Close Video loop Thread
        self.logger.debug("Stop Video loop thread.")
        self.stop_thread_event.set()

        # Close Window
        self.logger.debug("Close window.")
        self.window.quit()
Exemple #54
0
class IviGui:
    def __init__(self, master):
        self.master = master
        master.title("U2001A power measurement")

        # Label and Entry for inputting relative/attenuator value
        self.atten = Label(master, text="Relative (dB):")
        self.atten.grid(row=1, column=1)
        self.entry = Entry(master)
        self.entry.insert(0, '0')
        self.entry.grid(row=1, column=2)

        # Main display label. Shows relative measurement with dot during updates
        self.label = Label(master,
                           text=" \n-NaN dBm",
                           font=("Arial", 32),
                           height=3,
                           width=20)
        self.label.grid(row=2, column=1, columnspan=2)
        # Smaller secondary display to show real measurement by device
        self.label2 = Label(master, text=" \n-NaN dBm", font=("Arial", 16))
        self.label2.grid(row=3, column=1, columnspan=2)

        print usbtmc.list_resources()  # List USBTMC resources to connect to.
        self.instr = usbtmc.Instrument(
            'USB::10893::11032::INSTR'
        )  # Your device to connect to. Pick from the list.
        self.instr.timeout = 60 * 1000  # Some devices are slow, some configurations are slow, timeout in ms.
        print self.instr.ask(
            "*IDN?"
        )  # Print out what device itself thinks its name is for validation.

        # Keysight U2001A trigger setup - free running trigger
        self.instr.write("INIT[1]:CONT 1")
        self.instr.write("TRIG[1]:SOUR IMM")

        # Init the variables
        self.measurement = -100
        self.original_background = self.entry.cget("background")

        # Start first measurement
        self.update()

    # This method polls the device and updates display. Polling can take long time.
    def update(self):
        self.measurement = self.instr.ask("MEAS?")
        #print "%.2f" % float(self.measurement)      # Debug printout to check the connection.

        self.update_number(True)
        self.label.after(100, self.remove_dot)

    # 100 ms after getting a measurement from the device, remove the dot above the measurement.
    # This provided clear indication to user about when the data was updated.
    def remove_dot(self):
        self.update_number(False)
        self.label.after(100, self.update)

    # Deal with getting the relative number from the Entry and updating all the displays.
    def update_number(self, dot=False):
        try:
            relative_value = float(self.entry.get())
            self.entry.config(background=self.original_background)

            if dot:
                self.label.config(text=".\n%.2f dBm" %
                                  (float(self.measurement) - relative_value))
            else:
                self.label.config(text=" \n%.2f dBm" %
                                  (float(self.measurement) - relative_value))

        # If the relative box shows gibberish, just display the measurement.
        except ValueError:
            self.entry.config(background="#A44")

            if dot:
                self.label.config(text=".\n%.2f dBm" % float(self.measurement))
            else:
                self.label.config(text=" \n%.2f dBm" % float(self.measurement))

        self.label2.config(text="%.2f dBm" % float(self.measurement))
class RentalPaymentWindow(Frame):
    def __init__(self, parent, graphics):
        Frame.__init__(self)
        self.parent = parent
        self.graphics = graphics
        self.config(bg=self.graphics.mainColor)
        self.selected = ""
        self.font = tkFont.Font(family="Courier", size=12)
        #self.color = '#FFFFFF'

        #Title Label
        self.outputLabel = Label(self, text="", bg=self.graphics.mainColor)
        self.outputLabel.grid(row=0, column=0, sticky='ns', padx=6, pady=5)

        #Title Label
        self.creditCardNumberLabel = Label(self,
                                           text="Credit Card Number",
                                           bg=self.graphics.mainColor)
        self.creditCardNumberLabel.grid(row=2,
                                        column=0,
                                        sticky='ns',
                                        padx=6,
                                        pady=5)

        #Manual Enter Output
        self.creditCardNumber = Entry(self, width=20)
        self.creditCardNumber.grid(row=2, column=1, sticky='ns', padx=6)

        #Title Label
        self.nameLabel = Label(self,
                               text="Enter Name",
                               bg=self.graphics.mainColor)
        self.nameLabel.grid(row=3, column=0, sticky='ns', padx=6, pady=5)

        #Manual Enter Output
        self.name = Entry(self, width=20)
        self.name.grid(row=3, column=1, sticky='ns', padx=6)

        self.addressLabel = Label(self,
                                  text="Enter Address",
                                  bg=self.graphics.mainColor)
        self.addressLabel.grid(row=4, column=0, sticky='ns', padx=6, pady=5)

        #Manual Enter Output
        self.address = Entry(self, width=20)
        self.address.grid(row=4, column=1, sticky='ns', padx=6)

        self.submitButton = Button(self,
                                   text="Submit",
                                   width=15,
                                   command=lambda: self.submit())
        self.submitButton.grid(row=5, column=0)

        self.cancelButton = Button(self,
                                   text="Cancel",
                                   width=15,
                                   command=lambda: self.cancel())
        self.cancelButton.grid(row=5, column=1)

#		Style().configure('green/black.TButton', foreground='black', background='black')
#
#		self.L1 = Entry(self,state = DISABLED, disabledforeground = parent.cget('bg'))
#		self.L1.pack()#

#		self.B1 = Button(self, text = "Are You Alive???", command = self.hello)
#		self.B1.pack()#

#		self.B2 = Button(self, text = "DISSAPEAR???", command = self.goodbye)
#		self.B2.pack()

    def submit(self):
        self.creditCardNumber.config(text="f")
        self.name.config(text="f")
        self.address.config(text="f")
        number = self.creditCardNumber.get()
        name = self.name.get()
        payment = Payment(self.selected, number)

        self.graphics.POS.getCurrentTransaction().setPayment(payment)
        self.complete()

    def cancel(self):
        self.graphics.liftLayer("transaction")

    def credit(self):
        print "credit"

    def complete(self):
        self.creditCardNumber.config(text="")
        self.name.config(text="")
        self.outputLabel.config(text=" ")

        print "completing transaction"

        #color = "#D1D1D1"
        color = "#e8e8e8"
        width = 35

        # Create progress bar pop-up window
        receiptWindow = Toplevel(self)
        receiptWindow.configure(bg=color)
        #Should be 7.35 x width
        receiptWindow.geometry("500" + "x" + str(
            int(13.05 *
                (len(self.graphics.POS.getTransactionReceipt().split('\n')) +
                 5) + 100)) + "+150+50")
        self.graphics.POS.completeStuff()
        # Text Field Object, used in the submission function
        receiptText = Label(
            receiptWindow,
            text=self.graphics.POS.getTransactionReceipt(),
            bg='white',
            font=self.font)  #self.graphics.POS.getTransactionReceipt()
        receiptText.pack(side="top")
        #self.itemIDField.delete(0, 'end')
        self.graphics.liftLayer("main")
Exemple #56
0
class WSGui(threading.Thread):  #Word Suggester GUI
    '''
    Creates the GUI when initialized, and allows the word displayed in the
    box to update. The GUI will always be "in-front" of other application
    windows, so that it will always be visible.
    '''
    def __init__(self,
                 bg,
                 corner,
                 dcm,
                 fontsize,
                 txtcolor,
                 Q,
                 height=2,
                 width=40):
        threading.Thread.__init__(self)
        self.root = Tk()

        self.dcm = dcm
        self.q = Q
        self.fg = txtcolor

        # Convert corner string into appropriate newGeometry value for
        # root.geometry(). This functionality is Windows OS specific.
        if corner == "topright":
            newGeometry = "-1+1"
        elif corner == "topleft":
            newGeometry = "+1+1"
        elif corner == "bottomright":
            newGeometry = "-1-1"
        elif corner == "bottomleft":
            newGeometry = "+1-1"
        else:
            raise ValueError("GUI corner string has unrecognized value.")

        # Set the window to always be visible, but be non-interactable
        self.root.wm_attributes("-topmost", 1)
        self.root.overrideredirect(1)

        # Create the variable to store the text to display
        self.textvar = StringVar()

        # Create the label widget to pack into the root window
        self.label = Label(self.root,
                           anchor=CENTER,
                           background=bg,
                           fg=self.fg,
                           font=('', fontsize),
                           textvariable=self.textvar,
                           height=height,
                           width=width)
        self.label.pack(expand=0, fill=None)

        # Place the window where specified by the corner parameter
        self.root.geometry(newGeometry)

        if self.dcm == True:
            self.root.withdraw()

    def run(self):
        self.root.after(1000, self.poll)
        self.root.mainloop()

    def poll(self):
        try:
            word = self.q.get(block=True)
        except Queue.Empty:
            print "THIS SHOULDN'T HAPPEN. CRY DEEPLY THAT I CODED NO REAL \
EXCEPTION HANDLING."

        while not self.q.empty():
            word = self.q.get()
        if type(word) is str:
            if self.dcm == False:
                self.update_word(word)
        elif type(word) is list:
            options_list = word
            self.update_config(options_list)
        elif word == 1:
            self.flash_color()
        elif word == 0:
            self.end()
            return
        if self.dcm != True:
            self.root.after(100, self.poll)
        else:
            self.root.after(2000, self.poll)

    def update_word(self, word):
        #updates the text displayed, changing it to the word string passed in
        self.textvar.set(word)
        self._update_idle()

    def update_config(self, options_l):
        GUI_size, GUI_corner, GUI_bg, GUI_txtcolor, GUI_fontsize, DCM, p_s, spc, p_n = options_l
        if GUI_size == "small":
            GUI_height = 1
            GUI_width = 20
        elif GUI_size == "normal":
            GUI_height = 2
            GUI_width = 40
        elif GUI_size == "large":
            GUI_height = 3
            GUI_width = 60

        if GUI_corner == "topright":
            newGeometry = "-1+1"
        elif GUI_corner == "topleft":
            newGeometry = "+1+1"
        elif GUI_corner == "bottomright":
            newGeometry = "-1-1"
        elif GUI_corner == "bottomleft":
            newGeometry = "+1-1"

        if GUI_fontsize == "small":
            fontsize = 15
        elif GUI_fontsize == "normal":
            fontsize = 25
        elif GUI_fontsize == "large":
            fontsize = 35

        if DCM == True:
            if self.dcm != DCM:
                self.root.withdraw()
        elif DCM == False:
            if self.dcm != DCM:
                self.root.deiconify()
        self.dcm = DCM

        self.fg = GUI_txtcolor

        self.label.config(bg=GUI_bg,
                          fg=self.fg,
                          font=('', fontsize),
                          height=GUI_height,
                          width=GUI_width)

        self.root.geometry(newGeometry)

    def flash_color(self, color="blue", color_opt="black"):
        ''' Sets the text to the color, passed in as a string. '''
        if self.fg != color:
            self.label.config(fg=color)
        else:
            self.label.config(fg=color_opt)
        self._update_idle()
        self.root.after(100, self._reset_color)

    def end(self):
        try:
            self.root.destroy()
        except Exception as e:
            print(e)
            print "ROOT DID NOT DESTROY"

    def _update_idle(self):
        self.root.update_idletasks()

    def _reset_color(self):
        self.label.config(fg=self.fg)
Exemple #57
0
"""
Code illustration: 8.08
tkfont Demo
Tkinter GUI Application Development Hotshot
"""

from Tkinter import Tk, Label, Pack
import tkFont
root = Tk()
label = Label(root, text="Humpty Dumpty was pushed")
label.pack()
currentfont = tkFont.Font(font=label['font'])
print 'Actual :' + str(currentfont.actual())
print 'Family : ' + currentfont.cget("family")
print 'Weight : ' + currentfont.cget("weight")
print 'Text width of Dumpty : %d' % currentfont.measure("Dumpty")
print 'Metrics:' + str(currentfont.metrics())
currentfont.config(size=14)
label.config(font=currentfont)
print 'New Actual :' + str(currentfont.actual())
root.mainloop()
class ReactionProperties:
    """Gets the model types for each of the layers in the system."""

    def __init__(self, master, system):
        """Constructor method. Used to defines the layers."""
        
        self.master         = master
        self.system         = system
        self.version        = system.version
        self.fonttype       = system.fonttype
        self.formulatype    = system.formulatype
        self.superfont      = get_superfont(self.fonttype)
        self.subfont        = get_superfont(self.formulatype)
        self.tframe         = Frame(master.tframe)
        self.frame          = Frame(master.frame)
        self.bframe         = Frame(master.bframe)
        self.bgcolor        = self.frame.cget('bg')
        self.top            = None

        self.chemicals      = system.chemicals
        
        if master.master is None: self.defaults = 1

        if system.reactions is None: self.reactions      = []
        else:                        self.reactions      = system.reactions
        
    def make_widgets(self):
        """Makes the widgets for the GUI."""

        self.instructions   = Label(self.tframe,  text  = 'Please input the kinetic processes in the system:        ')

        self.blankcolumn    = Label(self.tframe,  text = '', font = 'courier 10',  width = 1 )
        self.editcolumn     = Label(self.tframe,  text = '', font = 'courier 10',  width = 6 )
        self.delcolumn      = Label(self.tframe,  text = '', font = 'courier 10',  width = 6 )
        self.numbercolumn   = Label(self.tframe,  text = '', font = 'courier 10',  width = 5 )
        self.namecolumn     = Label(self.tframe,  text = '', font = 'courier 10',  width = 15)
        self.equationcolumn = Label(self.tframe,  text = '', font = 'courier 10',  width = 20)
        self.ratecolumn     = Label(self.tframe,  text = '', font = 'courier 10',  width = 10)
        self.endcolumn      = Label(self.tframe,  text = '', font = 'courier 10',  width = 2)
        
        self.numberlabel    = Label(self.tframe,  text = 'Number')
        self.namelabel      = Label(self.tframe,  text = 'Name')
        self.equationlabel  = Label(self.tframe,  text = 'Chemical equation')
        self.ratelabel      = Label(self.tframe,  text = 'Rate equation')

        self.botblankcolumn    = Label(self.frame,  text = '', font = 'courier 10',  width = 1 )
        self.boteditcolumn     = Label(self.frame,  text = '', font = 'courier 10',  width = 6 )
        self.botdelcolumn      = Label(self.frame,  text = '', font = 'courier 10',  width = 6 )
        self.botnumbercolumn   = Label(self.frame,  text = '', font = 'courier 10',  width = 5 )
        self.botnamecolumn     = Label(self.frame,  text = '', font = 'courier 10',  width = 15)
        self.botequationcolumn = Label(self.frame,  text = '', font = 'courier 10',  width = 20)
        self.botratecolumn     = Label(self.frame,  text = '', font = 'courier 10',  width = 10)
        self.botendcolumn      = Label(self.frame,  text = '', font = 'courier 10',  width = 2)

        self.addwidget      = Button(self.bframe, text = 'Add reactions', command = self.addreaction, width = 20)
        self.blank1         = Label (self.bframe, text = ' ')
        self.blank2         = Label (self.bframe, text = ' ')
        #show the widgets on the grid

        self.instructions.grid( row = 0, column = 0, padx = 8, columnspan = 6, sticky = 'W')

        self.blankcolumn.grid(      row = 1, column = 0, padx = 1, sticky = 'WE', pady = 1)
        self.editcolumn.grid(       row = 1, column = 1, padx = 1, sticky = 'WE', pady = 1)
        self.delcolumn.grid(        row = 1, column = 2, padx = 1, sticky = 'WE', pady = 1)
        self.numbercolumn.grid(     row = 1, column = 3, padx = 4, sticky = 'WE')
        self.namecolumn.grid(       row = 1, column = 4, padx = 4, sticky = 'WE')
        self.equationcolumn.grid(   row = 1, column = 5, padx = 4, sticky = 'WE')
        self.ratecolumn.grid(       row = 1, column = 6, padx = 4, sticky = 'WE')
        self.endcolumn.grid(        row = 1, column = 7, padx = 4, sticky = 'WE')

        self.numberlabel.grid(      row = 2, column = 3, padx = 1, sticky = 'WE', pady = 4)
        self.namelabel.grid(        row = 2, column = 4, padx = 1, sticky = 'WE', pady = 4)
        self.equationlabel.grid(    row = 2, column = 5, padx = 1, sticky = 'WE', pady = 4)
        self.ratelabel.grid(        row = 2, column = 6, padx = 1, sticky = 'WE', pady = 4)

        self.updatereactions()
        
    def updatereactions(self):
        
        self.addwidget.grid_forget()
        self.blank1.grid_forget()
        self.blank2.grid_forget()

        namelabellength         = 15
        equationlabellength     = 20
        ratelabellength         = 10

        row = 4
        
        for reaction in self.reactions:
            try: reaction.remove_propertieswidgets()
            except:pass
            reaction.number = self.reactions.index(reaction) + 1
            reaction.propertieswidgets(self.frame, row, self.master, self.formulatype, self.superfont, self.subfont, self.bgcolor)
            row = row + 1

            if namelabellength     < reaction.namelabel.winfo_reqwidth()/8:  namelabellength     = int(reaction.namelabel.winfo_reqwidth()/8) + 1
            if equationlabellength < reaction.equalabel.winfo_reqwidth()/8:  equationlabellength = int(reaction.equalabel.winfo_reqwidth()/8) + 1
            if ratelabellength     < reaction.ratewidget.winfo_reqwidth()/8: ratelabellength     = int(reaction.ratewidget.winfo_reqwidth()/8) + 1

        self.botblankcolumn.grid(      row = row, column = 0, padx = 1, sticky = 'WE',pady = 1)
        self.boteditcolumn.grid(       row = row, column = 1, padx = 1, sticky = 'WE',pady = 1)
        self.botdelcolumn.grid(        row = row, column = 2, padx = 1, sticky = 'WE',pady = 1)
        self.botnumbercolumn.grid(     row = row, column = 3, padx = 4, sticky = 'WE')
        self.botnamecolumn.grid(       row = row, column = 4, padx = 4, sticky = 'WE')
        self.botequationcolumn.grid(   row = row, column = 5, padx = 4, sticky = 'WE')
        self.botratecolumn.grid(       row = row, column = 6, padx = 4, sticky = 'WE')
        self.botendcolumn.grid(        row = row, column = 7, padx = 4, sticky = 'WE')

        self.namecolumn.config(width     = namelabellength)
        self.equationcolumn.config(width = equationlabellength)
        self.ratecolumn.config(width     = ratelabellength)

        self.botnamecolumn.config(width     = namelabellength)
        self.botequationcolumn.config(width = equationlabellength)
        self.botratecolumn.config(width     = ratelabellength)


        row = 0

        self.blank1.grid(row = row)
        row = row + 1
        self.blank2.grid(row = row)
        row = row + 1

        self.addwidget.grid(row = row, columnspan = 11)
        row = row + 1

        self.focusbutton = None
        self.master.geometry()
        self.master.center()

    def addreaction(self, event = None):

        self.reactions.append(Reaction(len(self.reactions)+1))
        
        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(ReactionEditor(self.top, self.system, self.reactions[-1], editflag = 0))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0: self.reactions[-1].get_reaction(self.top.window)
            else:
                self.reactions.remove(self.reactions[-1])
                
            if self.top is not None:
                self.top.destroy()
                self.top = None
                
        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()
                    
        self.updatereactions()
                    
    def editreaction(self, number):

        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(ReactionEditor(self.top, self.system, self.reactions[number-1], editflag = 1))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0: self.reactions[number-1].get_reaction(self.top.window)
                
            if self.top is not None:
                self.top.destroy()
                self.top = None
                
        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()
        
        self.updatereactions()
        

    def delreaction(self, number):
        
        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(ReactionDeleter(self.top, self.system, self.reactions[number-1]))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                self.reactions[number-1].remove_propertieswidgets()
                self.reactions.remove(self.reactions[number-1])
                
            if self.top is not None:
                self.top.destroy()
                self.top = None
                
        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()
        
        self.updatereactions()
class LayerProperties:
    """Input the parameters for each of the layers in the system."""

    def __init__(self, master, system, editflag = None):
        """Constructor method. Used to defines the layers."""
        
        self.fonttype     = system.fonttype
        self.version      = system.version
        self.master       = master
        self.frame        = Frame(master.frame)
        self.tframe       = Frame(master.tframe)
        self.bframe       = Frame(master.bframe)
        self.superfont    = get_superfont(self.fonttype)
        self.top          = None

        self.system       = system
        self.lengthunit   = system.lengthunit

        if system.layers is None:
            self.layers  = []
            self.nlayers = 0
        else:
            self.layers  = system.layers
            self.nlayers = system.nlayers

        self.editflag = editflag

        print(editflag)
        if editflag == 1:
            self.num_record         = [j for j in range(self.nlayers)]

    def make_widgets(self):
        """Make the widgets for the window."""
  
        self.instructions = Label(self.tframe,  text = 'Starting with the layer nearest the overlying water, please ' +
                                  'provide the following information for each layer:' + ' '*20, justify = 'left')

        self.blankcolumn    = Label(self.tframe, text = '', font = 'courier 10', width = 1)
        self.editcolumn     = Label(self.tframe, text = '', font = 'courier 10', width = 6)
        self.delcolumn      = Label(self.tframe, text = '', font = 'courier 10', width = 6)
        self.namecolumn     = Label(self.tframe, text = '', font = 'courier 10', width = 12)
        self.typecolumn     = Label(self.tframe, text = '', font = 'courier 10', width = 15)
        self.tortcolumn     = Label(self.tframe, text = '', font = 'courier 10', width = 20)
        self.thickcolumn    = Label(self.tframe, text = '', font = 'courier 10', width = 10)
        self.alphacolumn    = Label(self.tframe, text = '', font = 'courier 10', width = 15)
        self.doccolumn      = Label(self.tframe, text = '', font = 'courier 10', width = 20)
        self.endcolumn      = Label(self.tframe, text = '', font = 'courier 10', width = 2)
        #Title Widgets

        self.material    = Label(self.tframe, text = 'Material')
        self.tortuosity  = Label(self.tframe, text = 'Tortuosity Correction ')
        self.thickness   = Label(self.tframe, text = 'Thickness')
        self.alpha       = Label(self.tframe, text = 'Hydrodynamic\n'+'Dispersivity')
        self.doclabel    = Label(self.tframe, text = 'Dissolved organic\n'+'matter concentration   ')
        
        #Unit Widgets
        
        self.thickunits  = Label(self.tframe, text = self.lengthunit)
        self.alphaunits  = Label(self.tframe, text = self.lengthunit)
        self.docunits    = Label(self.tframe, text = 'mg/L')
        
        self.botblankcolumn    = Label(self.frame, text = '', font = 'courier 10', width = 1)
        self.boteditcolumn     = Label(self.frame, text = '', font = 'courier 10', width = 6)
        self.botdelcolumn      = Label(self.frame, text = '', font = 'courier 10', width = 6)
        self.botnamecolumn     = Label(self.frame, text = '', font = 'courier 10', width = 12)
        self.bottypecolumn     = Label(self.frame, text = '', font = 'courier 10', width = 15)
        self.bottortcolumn     = Label(self.frame, text = '', font = 'courier 10', width = 20)
        self.botthickcolumn    = Label(self.frame, text = '', font = 'courier 10', width = 10)
        self.botalphacolumn    = Label(self.frame, text = '', font = 'courier 10', width = 15)
        self.botdoccolumn      = Label(self.frame, text = '', font = 'courier 10', width = 20)
        self.botendcolumn      = Label(self.frame, text = '', font = 'courier 10', width = 2)
        #a special OK button is needed to check bioturbation depth
        
        self.blank1 = Label(self.bframe, text = ' ')
        self.blank2 = Label(self.bframe, text = ' ')

        self.addwidget  = Button(self.bframe, text = 'Add layers', command = self.addlayer, width = 20)

        #show the widgets on the grid
        self.instructions.grid(row = 0, column = 0, padx = 6, sticky = 'W', columnspan = 10)
        
        self.blankcolumn.grid(  row = 1,  column = 0)
        self.editcolumn.grid(   row = 1,  column = 1)
        self.delcolumn.grid(    row = 1,  column = 2)
        self.namecolumn.grid(   row = 1,  column = 3)
        self.typecolumn.grid(   row = 1,  column = 5)
        self.tortcolumn.grid(   row = 1,  column = 4)
        self.thickcolumn.grid(  row = 1,  column = 6)
        self.alphacolumn.grid(  row = 1,  column = 7)
        self.doccolumn.grid(    row = 1,  column = 8)
        self.endcolumn .grid(   row = 1,  column = 9)

        self.material.grid(     row = 2,  column = 4, padx = 0, sticky = 'N')
        self.tortuosity.grid(   row = 2,  column = 5, padx = 0, sticky = 'N')
        self.thickness.grid(    row = 2,  column = 6, padx = 0, sticky = 'N')
        self.alpha.grid(        row = 2,  column = 7, padx = 0, sticky = 'N')
        self.doclabel.grid(     row = 2,  column = 8, padx = 0, sticky = 'N')

        self.thickunits.grid(   row = 3,  column = 6, padx = 0)
        self.alphaunits.grid(   row = 3,  column = 7, padx = 0)
        self.docunits.grid(     row = 3,  column = 8, padx = 0)

        #make entry widgets for each of the layers
        self.updatelayers()
       
    def updatelayers(self):

        self.addwidget.grid_forget()
        self.blank1.grid_forget()
        self.blank2.grid_forget()

        namelabellength = 20

        for layer in self.layers:
            try: layer.remove_propertywidgets()
            except: pass
            if self.layers[0].number == 0:  layer.number = self.layers.index(layer)
            else:                           layer.number = self.layers.index(layer) + 1
            if layer.number == 0:           layer.name   = 'Deposition'
            else:                           layer.name   = 'Layer ' + str(layer.number)

        row = 4
        for layer in self.layers:
            layer.propertywidgets(self.frame, row, self.master)
            row = row + 1
            if namelabellength < layer.typelabel.winfo_reqwidth()/8:  namelabellength = int(layer.typelabel.winfo_reqwidth()/8) + 1

        self.typecolumn.config(width = namelabellength)
        self.bottypecolumn.config(width = namelabellength)

        self.botblankcolumn.grid(  row = row,  column = 0)
        self.boteditcolumn.grid(   row = row,  column = 1)
        self.botdelcolumn.grid(    row = row,  column = 2)
        self.botnamecolumn.grid(   row = row,  column = 3)
        self.bottypecolumn.grid(   row = row,  column = 5)
        self.bottortcolumn.grid(   row = row,  column = 4)
        self.botthickcolumn.grid(  row = row,  column = 6)
        self.botalphacolumn.grid(  row = row,  column = 7)
        self.botdoccolumn.grid(    row = row,  column = 8)
        self.botendcolumn .grid(   row = row,  column = 9)

        self.blank1.grid(row = row)
        row = row + 1
        self.blank2.grid(row = row)
        row = row + 1
        self.addwidget.grid(row = row, columnspan = 11)
        row = row + 1

        self.addwidget.bind('<Return>', self.addlayer)

        if self.nlayers == 0:   self.focusbutton = self.addwidget#self.okbutton
        else:                   self.focusbutton = None
        self.master.geometry()
        self.master.center()

    def addlayer(self, default = None):

        self.nlayers = self.nlayers + 1
        layertemp = Layer(1)

        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(LayerEditor(self.top, self.system, layertemp, self.layers, editflag = 0))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                layertemp.get_layer(self.top.window)
                if self.layers == []:            self.layers.append(layertemp)
                elif self.layers[0].number == 0: self.layers.insert( layertemp.number,    layertemp)
                elif layertemp.number == 0:      self.layers.insert( 0,                   layertemp)
                else:                            self.layers.insert( layertemp.number-1,  layertemp)

                if self.editflag == 1:
                    if self.layers[0].number == 0:
                        self.num_record.insert( layertemp.number,    -1)
                    elif layertemp.number == 0:
                        self.num_record.insert( 0,                   -1)
                    else:
                        self.num_record.insert( layertemp.number-1,  -1)

            else:
                self.nlayers = self.nlayers - 1
                layertemp = 0

            if self.top is not None:
                self.top.destroy()
                self.top = None
                
        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()


        self.updatelayers()

    def editlayer(self, number):
        
        if self.layers[0].number == 0: layertemp = self.layers[number]
        else:                          layertemp = self.layers[number-1]

        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(LayerEditor(self.top, self.system, layertemp, self.layers, editflag = 1))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                layertemp.get_layer(self.top.window)
               
            if self.top is not None:
                self.top.destroy()
                self.top = None
                
        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()
            
        self.updatelayers()
        
    def deletelayer(self, number):

        if self.layers[0].number == 0: layer = self.layers[number]
        else:                          layer = self.layers[number - 1]
        
        if self.top is None:

            self.top = CapSimWindow(master = self.master, buttons = 2)
            self.top.make_window(LayerDeleter(self.top, self.system, layer))
            self.top.tk.mainloop()

            if self.top.window.cancelflag == 0:
                layer.remove_propertywidgets()
                if self.editflag == 1:
                    new_record      = self.num_record[:self.layers.index(layer)] + self.num_record[self.layers.index(layer)+1:]
                    self.num_record = new_record
                self.layers.remove(layer)
                self.nlayers = self.nlayers - 1

            if self.top is not None:
                self.top.destroy()
                self.top = None
                
        elif self.top is not None:
            tkmb.showerror(title = self.system.version, message = 'Please close the existing parameter input window first.')
            self.top.tk.focus()
            
        self.updatelayers()

    def error_check(self, event = None):
        """Finish and move on.  Checks that the number chemicals are less than the
        total number of chemicals in database."""

        error = 0
        if self.nlayers == 0: error = 1
        elif self.nlayers == 1 and self.layers[0].number ==0: error = 1

        return error

    def warning(self):

        tkmb.showerror(title = self.version, message = 'No layer has been created, please add layers by pressing the button "Add layers"')
        self.focusbutton = None
        self.master.tk.lift()
Exemple #60
0
class Splash(Tk):
    def __init__(self):
        Tk.__init__(self)

        # frame
        self.frame = Frame(self, padx=10, pady=10, bd=1, relief=RAISED)
        self.frame.pack()

        # logo
        logo = Image.open(os.path.join(settings.img_dir, 'logo_big.png'))
        logo = logo.convert('RGBA')
        r, g, b, logo_alpha = logo.split()

        # load image
        self.angle = 0
        circle = Image.open(os.path.join(settings.img_dir, 'circle_big.png'))
        circle = circle.convert('RGBA')
        img = ImageTk.PhotoImage(circle, master=self)

        # status text
        self.text = StringVar()

        # center window to screen
        x = (self.winfo_screenwidth() - img.width()) // 2
        y = (self.winfo_screenheight() - img.height()) // 2
        self.geometry('+{}+{}'.format(x, y))

        self.overrideredirect(True)
        self.wm_attributes("-topmost", 1)
        self.focus_force()

        self.update()

        self.index = 0
        self.angles = list()
        for i in xrange(0, 360, 5):
            img = circle.rotate(i)
            img.paste(logo, mask=logo_alpha)
            img = ImageTk.PhotoImage(img, master=self)
            self.angles.append(img)

        self.w = Label(self.frame, padx=5, pady=5)
        self.w.image = img
        self.w.pack()

        self.greenlet = gevent.spawn_later(0.015, self.animate)
        self.info_greenlet = gevent.spawn_later(50, self.show_info)

    def animate(self):
        self.index += 1
        if len(self.angles) == self.index:
            self.index = 0
        img = self.angles[self.index]
        self.w.config(image=img)
        self.update()
        self.angle += 4
        if self.angle > 360:
            self.angle = 0
        self.greenlet = gevent.spawn_later(0.02, self.animate)

    def show_info(self):
        w = Label(self.frame, textvariable=self.text, padx=5, pady=5)
        w.pack()
        self.update()

    def set_text(self, text):
        self.text.set('\n'.join(text.split(': ', 1)))
        self.update()

    def show(self):
        self.deiconify()
        self.update()

    def hide(self):
        self.withdraw()

    def close(self):
        self.greenlet.kill()
        if self.info_greenlet:
            self.info_greenlet.kill()
        self.destroy()