def __init__(self):
        window=Tk()
        window.title('Scientific Calculator')
        window.configure(background="white")
        self.string=StringVar()
        entry=Entry(window,textvariable=self.string)
        entry.grid(row=0,column=0,columnspan=6)
        entry.configure(background="white")
        entry.focus()
        
        values=["7","8","9","/","%","clear","AC",
                "4","5","6","*","(",")","**",
                "1","2","3","-","=",",","0",".","min","+","sin","asin","cos","acos","tan()",
                "pow","log10","max","abs","floor","pi","e","log","ceil","degrees","radians"]
        text=1
        i=0
        row=1
        col=0
        for txt in values:
            padx=10
            pady=10
            if(i==7):
                row=2
                col=0
            if(i==14):
                row=3
                col=0
            if(i==19):
                row=4
                col=0
            if(i==26):
                row=5
                col=0
            if(i==33):
                row=6
                col=0
            if(txt=='='):
                btn=Button(window,height=2,width=4,padx=70,pady=pady,text=txt,command=lambda txt=txt:self.equals())
                btn.grid(row=row,column=col,columnspan=3,padx=2,pady=2)
                btn.configure(background="yellow")

            elif(txt=='clear'):
                btn=Button(window,height=2,width=4,padx=padx,pady=pady, text=txt ,command=lambda txt=txt:self.delete())
                btn.grid(row=row,column=col,padx=1,pady=1)
                btn.configure(background="grey")
            elif(txt=='AC'):
                btn=Button(window,height=2,width=4,padx=padx,pady=pady,text=txt,command=lambda txt=txt:self.clearall())
                btn.grid(row=row,column=col,padx=1,pady=1)
                btn.configure(background="red")
            else:
                btn=Button(window,height=2,width=4,padx=padx,pady=pady,text=txt ,command=lambda txt=txt:self.addChar(txt))
                btn.grid(row=row,column=col,padx=1,pady=1)
                btn.configure(background="cyan")

            col=col+1
            i=i+1
        window.mainloop()
예제 #2
0
    def ask_title_and_create_window(self):
        toplevel = Toplevel()
        
        label = Label(toplevel, text="Title:")
        label.pack(anchor=W)

        entry = Entry(toplevel, width=15)
        entry.pack(anchor=W, fill=X)
        
        entry.bind("<Return>", lambda event: (self.new_window(entry.get()), toplevel.destroy()))
        
        entry.focus()
        
        return "break"
예제 #3
0
class popupWindow(object):
    def __init__(self,master, title):
        self.top=Toplevel(master)
        self.value = ''
        self.top.geometry("+300+300")
        self.l=Label(self.top,text=title)
        self.l.pack()
        self.e=Entry(self.top)
        self.e.pack()
        self.b=Button(self.top,text='Ok',command=self.cleanup)
        self.b.pack()
        self.e.focus()
    def cleanup(self):
        self.value=self.e.get()
        self.top.destroy()
예제 #4
0
 def __init__(self):
     window=Tk()
     window.title('Calculator')
     window.configure(background="black")
     self.string=StringVar()
     entry=Entry(window,textvariable=self.string)
     entry.grid(row=0,column=0,columnspan=20)
     entry.configure(background="white")
     entry.focus()        
     values=["7","8","9","/","%","clear",
             "4","5","6","*","+","AC",
             "1","2","3","-","0","="]
     text=1
     i=0
     row=1
     col=0
     for txt in values:
         padx=5
         pady=5
         if(i==6):
             row=2
             col=0
         if(i==12):
             row=3
             col=0
         if(i==18):
             row=4
             col=0
         
         if(txt=='='):
             btn=Button(window,height=2,width=4,padx=50,pady=pady,text=txt,command=lambda txt=txt:self.equals())
             btn.grid(row=row,column=col,columnspan=3,padx=1,pady=1)
             btn.configure(background="red")
         elif(txt=='clear'):
             btn=Button(window,height=2,width=4,padx=padx,pady=pady, text=txt ,command=lambda txt=txt:self.delete())
             btn.grid(row=row,column=col,padx=1,pady=1)
             btn.configure(background="yellow")
         elif(txt=='AC'):
             btn=Button(window,height=2,width=4,padx=padx,pady=pady,text=txt,command=lambda txt=txt:self.clearall())
             btn.grid(row=row,column=col,padx=1,pady=1)
             btn.configure(background="red")
         else:
             btn=Button(window,height=2,width=4,padx=padx,pady=pady,text=txt ,command=lambda txt=txt:self.addChar(txt))
             btn.grid(row=row,column=col,padx=1,pady=1)
             btn.configure(background="grey")
         col=col+1
         i=i+1
     window.mainloop()      
예제 #5
0
    def ask_title_and_create_window(self):
        toplevel = Toplevel()

        label = Label(toplevel, text="Title:")
        label.pack(anchor=W)

        entry = Entry(toplevel, width=15)
        entry.pack(anchor=W, fill=X)

        entry.bind(
            "<Return>", lambda event:
            (self.new_window(entry.get()), toplevel.destroy()))

        entry.focus()

        return "break"
예제 #6
0
    def prompt_gui(self, name, propagate_exception = False):
        ''' Returns None if failed to load tkinter or open display.
        (unless propagate_exception == True).'''
        
        ''' I thought about caching and reusing the tkinter instance, but it might be hard
        to properly temporarily exit from mainloop and suspend the application.
        Anyway, it takes like 10ms to restart it.'''
        try:
            from Tkinter import Tk, Label, Frame, Entry, StringVar
            root = Tk()
        except:
            if propagate_exception:
                raise
            return None

        root.title('Enter value for \'%s\':' % name)
        frame = Frame(root)
        frame.pack(fill = 'y', expand = True)

        label = Label(frame, text='Enter value for \'%s\':' % name)
        label.pack(side='left')
        
        var = StringVar()
        entry = Entry(frame, textvariable = var)
        entry.pack(side='left')
        
        result = []
        root.bind('<Return>', lambda ev: (result.append(var.get()), root.destroy()))
        ws = root.winfo_screenwidth()
        hs = root.winfo_screenheight()
        root.geometry('+%d+%d' % (ws * 0.4, hs * 0.4))
        entry.focus()
        
        # If I don't do this then for some reason the window doesn't get focus
        # on the second and following invocations. 
        root.focus_force()

        root.mainloop()
        if not len(result):
            # mimic the behaviour of CLI version
            raise KeyboardInterrupt()
        return result[0]
예제 #7
0
class EnterIPWindow(object):
    def __init__(self):
        self.serverAddress = 0
        self.setWindow()
        self.setEntryInput()
        self.setButtonOK()
        self.root.mainloop()

    def setWindow(self):
        self.root = Tkinter.Tk()
        windowWidth = 300
        windowHeight = 50
        screenWidth = self.root.winfo_screenwidth()
        screenHeight = self.root.winfo_screenheight()
        xPosition = (screenWidth / 2) - (windowWidth / 2)
        yPosition = (screenHeight / 2) - (windowHeight / 2)
        self.root.geometry('%dx%d+%d+%d' %
                           (windowWidth, windowHeight, xPosition, yPosition))
        self.root.title("Server IP Address")
        self.root.bind('<Return>', self.hitEnter)
        self.root.bind('<KP_Enter>', self.hitEnter)

    def setEntryInput(self):
        self.textInput = Entry(self.root)
        self.textInput.focus()
        self.textInput.pack()

    def setButtonOK(self):
        self.button = Tkinter.Button(self.root,
                                     text='OK',
                                     command=self.closeWindow)
        self.button.pack()

    def closeWindow(self, event=None):
        self.serverAddress = self.textInput.get()
        self.root.destroy()
        self.root.quit()

    def hitEnter(self, event):
        self.closeWindow(event)
예제 #8
0
    def __init__(self, mainWindow, mainWidth, mainHeight):

        frame_main = Frame(mainWindow, width=mainWidth, height=mainHeight)
        frame_main.grid(row=0, column=0)

        lblTitle = Label(mainWindow,
                         text="Ingrese su número de cédula",
                         font=(None, 45))
        lblTitle.place(x=self.posElement(50, mainWidth),
                       y=self.posElement(20, mainHeight),
                       anchor="center")

        #Validación de solo números
        #reg = mainWindow.register(val.onlyDigits)
        #reg = mainWindow.register()

        #txtCedula = Entry(mainWindow, font="Helvetica 60 bold", width=15, justify="center", validate="all", validatecommand=(reg, '%P'))
        txtCedula = Entry(mainWindow,
                          font="Helvetica 120 bold",
                          width=15,
                          justify="center")
        txtCedula.place(x=self.posElement(50, mainWidth),
                        y=self.posElement(50, mainHeight),
                        anchor="center")
        txtCedula.focus()

        lblTitle2 = Label(mainWindow,
                          text="Presione Click en 'ENTER' para continuar.",
                          font=(None, 45))
        lblTitle2.place(x=self.posElement(50, mainWidth),
                        y=self.posElement(80, mainHeight),
                        anchor="center")

        # Setup Keypad
        KEYPAD = [["3", "2", "1", "A"], ["6", "5", "4", "B"],
                  ["9", "8", "7", "C"], ["0", ".", "X", "D"]]

        # same as calling: factory.create_4_by_4_keypad, still we put here fyi:
        ROW_PINS = [
            16, 20, 21, 5
        ]  # BCM numbering; Board numbering is: 7,8,10,11 (see pinout.xyz/)
        COL_PINS = [
            6, 13, 19, 26
        ]  # BCM numbering; Board numbering is: 12,13,15,16 (see pinout.xyz/)

        factory = rpi_gpio.KeypadFactory()

        # Try keypad = factory.create_4_by_3_keypad() or
        # Try keypad = factory.create_4_by_4_keypad() #for reasonable defaults
        # or define your own:
        keypad = factory.create_keypad(keypad=KEYPAD,
                                       row_pins=ROW_PINS,
                                       col_pins=COL_PINS)

        def printkey(key):

            if self.estado == 0:
                if self.maxlong < 10:
                    if (key == '1' or key == '2' or key == '3' or key == '4'
                            or key == '5' or key == '6' or key == '7'
                            or key == '8' or key == '9' or key == '0'):
                        txtCedula.insert(END, key)
                elif key == 'D':
                    #FIXME Validar número de cédula

                    self.estado = 1

                    frame_menu.MenuForm(mainWindow, mainWidth, mainHeight)
                    mainWindow.update()
                    print "show"

                if key == 'X' or key == 'A':
                    txtCedula.delete(0, 'end')

                self.maxlong = len(txtCedula.get())

            elif self.estado == 1:
                if (key == '1'):
                    self.print_certificado_notas()
                elif key == '2':
                    self.print_certificado_matricula()

            print(key)

        keypad.registerKeyPressHandler(printkey)
예제 #9
0
class Chatbox(object):
    def __init__(self,
                 master,
                 my_nick=None,
                 command=None,
                 topic=None,
                 entry_controls=None,
                 maximum_lines=None,
                 timestamp_template=None,
                 scrollbar_background=None,
                 scrollbar_troughcolor=None,
                 history_background=None,
                 history_font=None,
                 history_padx=None,
                 history_pady=None,
                 history_width=None,
                 entry_font=None,
                 entry_background=None,
                 entry_foreground=None,
                 label_template=u"{nick}",
                 label_font=None,
                 logging_file=None,
                 tags=None):
        self.interior = Frame(master, class_="Chatbox")

        self._command = command

        self._is_empty = True

        self._maximum_lines = maximum_lines
        self._timestamp_template = timestamp_template

        self._command = command

        self._label_template = label_template

        self._logging_file = logging_file

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

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

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

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

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

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

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

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

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

        self._entry.focus()

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

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

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

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

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

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

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

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

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

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

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

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

        self.set_nick(my_nick)

    @property
    def topic(self):
        return

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

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

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

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

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

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

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

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

        self._write((content, tag))

    notification = notification_message

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

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

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

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

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

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

        self.user_message(self._my_nick, content)

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

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

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

        self._textarea.config(state=NORMAL)

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

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

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

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

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

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

        self._textarea.config(state=DISABLED)

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

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

        self.send(message)

        if self._command:
            self._command(message)

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

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

            self._entry_label["text"] = text
            self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry)
        else:
            self._entry_label.pack_forget()
예제 #10
0
class Chatbox(object):
    def __init__(self,
                 master,
                 my_nick=None,
                 command=None,
                 topic=None,
                 entry_controls=None,
                 maximum_lines=None,
                 timestamp_template=None,
                 scrollbar_background=None,
                 scrollbar_troughcolor=None,
                 history_background=None,
                 history_font=None,
                 history_padx=None,
                 history_pady=None,
                 history_width=None,
                 entry_font=None,
                 entry_background=None,
                 entry_foreground=None,
                 label_template=u"{nick}",
                 label_font=None,
                 logging_file='log.txt',
                 tags=None):
        self._master = master
        self.interior = Frame(master, class_="Chatbox")

        self._command = command

        self._is_empty = True

        self._maximum_lines = maximum_lines
        self._timestamp_template = timestamp_template

        self._command = command

        self._label_template = label_template

        self._logging_file = logging_file

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

        ####    INSTRUCTION:

        self.title_font = tkfont.Font(family='Helvetica',
                                      size=18,
                                      weight="bold")
        self.content_font = tkfont.Font(family='Helvetica', size=13)
        self.instruction_font = tkfont.Font(family='Courier', size=13)

        instruction_label_frame = Frame(self.interior,
                                        class_="Instruction_label")
        instruction_label_frame.pack(fill=X)

        self._label_instruction = Label(instruction_label_frame,
                                        text="INSTRUCTIONS",
                                        font=self.title_font)
        self._label_instruction.pack(side=LEFT)

        instruction_frame = Frame(self.interior, class_="Instruction")
        instruction_frame.pack(fill=X)

        self._text_instruction = Text(instruction_frame,
                                      height=13,
                                      borderwidth=2,
                                      relief="groove",
                                      font=self.instruction_font)
        self._text_instruction.pack(fill=X, side=LEFT, expand=True)
        quote = """1. Read the question.
2. Fill your answer  
   Please answer in a COMPLETE SENTENCE, not just keywords.    
   
   Example:
   Good:                                          Bad:
   Question: What kind of food do you like?       Question: What kind of food do you like?
   Reply: I like spicy food.                      Reply: spicy food.
   
   If you are reluctant to answer the question, click "Next Dialogue" button to go to the next question.
3. press Enter to submit your answer. 
4. Rate the reply question in the Evaluation section
5. Click "Next Dialogue" button at the bottom to continue. """
        self._text_instruction.insert(END, quote)

        counter_frame = Frame(self.interior)
        counter_frame.pack(fill=X)

        global counter_question
        counter_question = StringVar()
        counter_question.set(str(1))

        Label(counter_frame, text="").pack(side='top', anchor='w')
        self._label_counter_1 = Label(counter_frame,
                                      text="DIALOGUE",
                                      font=self.title_font).pack(side=LEFT)
        self._label_counter_2 = Label(counter_frame,
                                      textvariable=counter_question,
                                      font=self.title_font).pack(side=LEFT)
        self._label_counter_3 = Label(counter_frame,
                                      text="OF 10 ",
                                      font=self.title_font).pack(side=LEFT)

        ####     MESSAGE DISPLAY AREA:

        top_frame = Frame(self.interior, class_="Top")
        top_frame.pack(
            expand=True, fill=BOTH
        )  # True: the widget is expanded to fill any extra space, BOTH: fill X&Y

        self._textarea = Text(top_frame,
                              height=1,
                              borderwidth=2,
                              relief="groove",
                              state=DISABLED,
                              font=self.content_font)

        self._vsb = Scrollbar(top_frame,
                              takefocus=0,
                              command=self._textarea.yview)
        self._vsb.pack(side=RIGHT,
                       fill=Y)  #scroll bar di kanan, sepanjang sumbu Y

        self._textarea.pack(side=RIGHT, expand=YES, fill=BOTH)
        self._textarea.insert(END, '\n')
        self._textarea[
            "yscrollcommand"] = self._vsb.set  # text area tempat display chat

        ####     MESSAGE ENTRY:

        entry_frame = Frame(self.interior, class_="Chatbox_Entry")
        entry_frame.pack(
            fill=X, anchor=N
        )  # fill=X: make all widgets as wide as parent widget, anchor=N: place the text at the top

        #self.var_entry = StringVar()

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

            bottom_of_entry_frame = Frame(entry_frame)
            self._entry_label = Label(bottom_of_entry_frame)
            self._entry = Entry(
                bottom_of_entry_frame)  #,textvariable=self.var_entry
        else:
            self._entry_label = Label(entry_frame)
            self._entry = Entry(
                entry_frame)  #, width = 70, textvariable=self.var_entry

        self._entry.pack(side=LEFT, fill=X, expand=YES)
        self._entry.bind(
            "<Return>", self._on_message_sent
        )  # when user press enter in the chatbox, call on_message_sent
        self._entry.focus()

        #self._buttonmessage = Button(entry_frame, text="Submit", width = 20, command=self._on_message_sent)
        #self._buttonmessage.bind("<Button-1>", self._on_message_sent) # bind the action of the left button of your mouse to the button assuming your primary click button is the left one.
        #self._buttonmessage.pack(side=LEFT)

        ####

        label_evaluation = Frame(self.interior)
        label_evaluation.pack(fill=X, anchor=N)

        Label(label_evaluation, text="").pack(side='top', anchor='w')
        Label(label_evaluation, text="EVALUATION",
              font=self.title_font).pack(side='top', anchor='w')
        Label(
            label_evaluation,
            text=
            "Please indicate how strongly you agree or disagree with all the following statements."
        ).pack(side='top', anchor='w')
        #Label(label_evaluation, text="").pack(side='top', anchor='w')

        ####    QUESTIONNAIRES:
        ''' Questionnaire frame'''

        question_frame = Frame(self.interior)
        #question_frame.grid(column=0, row=0, sticky=(N, W, E, S))
        #question_frame.columnconfigure(0, weight=1)
        #question_frame.rowconfigure(0, weight=1)
        #self.configure(background="white")
        question_frame.pack()

        self.var_q1 = IntVar()
        self.var_q2 = IntVar()
        self.var_q3 = IntVar()
        self.var_q4 = IntVar()
        self.var_q1.set(0)  # none selected
        self.var_q2.set(0)  # none selected
        self.var_q3.set(0)  # none selected
        self.var_q4.set(0)  # none selected

        #Label(question_frame, text="").grid(column=0, row=0, sticky="W")
        #Label(question_frame, text="EVALUATION", font=self.title_font).grid(column=0, row=1, sticky="W")

        Label(question_frame, text="Strongly disagree").grid(column=1,
                                                             row=3,
                                                             padx=4)
        Label(question_frame, text="Disagree").grid(column=2, row=3, padx=4)
        Label(question_frame, text="Neither agree nor disagree").grid(column=3,
                                                                      row=3,
                                                                      padx=4)
        Label(question_frame, text="Agree").grid(column=4, row=3, padx=4)
        Label(question_frame, text="Strongly agree").grid(column=5,
                                                          row=3,
                                                          padx=4)

        Label(question_frame,
              text="The grammar of the reply question is correct").grid(
                  column=0, row=4, sticky="W")
        Radiobutton(question_frame, variable=self.var_q1,
                    value=1).grid(column=1, row=4)
        Radiobutton(question_frame, variable=self.var_q1,
                    value=2).grid(column=2, row=4)
        Radiobutton(question_frame, variable=self.var_q1,
                    value=3).grid(column=3, row=4)
        Radiobutton(question_frame, variable=self.var_q1,
                    value=4).grid(column=4, row=4)
        Radiobutton(question_frame, variable=self.var_q1,
                    value=5).grid(column=5, row=4)

        Label(
            question_frame,
            text=
            "The reply question is appropriate to be asked \nin a conversation",
            justify=LEFT).grid(column=0, row=5, sticky="W")
        Radiobutton(question_frame, variable=self.var_q2,
                    value=1).grid(column=1, row=5)
        Radiobutton(question_frame, variable=self.var_q2,
                    value=2).grid(column=2, row=5)
        Radiobutton(question_frame, variable=self.var_q2,
                    value=3).grid(column=3, row=5)
        Radiobutton(question_frame, variable=self.var_q2,
                    value=4).grid(column=4, row=5)
        Radiobutton(question_frame, variable=self.var_q2,
                    value=5).grid(column=5, row=5)

        Label(question_frame,
              text="The reply question is related to my answer").grid(
                  column=0, row=6, sticky="W")
        Radiobutton(question_frame, variable=self.var_q3,
                    value=1).grid(column=1, row=6)
        Radiobutton(question_frame, variable=self.var_q3,
                    value=2).grid(column=2, row=6)
        Radiobutton(question_frame, variable=self.var_q3,
                    value=3).grid(column=3, row=6)
        Radiobutton(question_frame, variable=self.var_q3,
                    value=4).grid(column=4, row=6)
        Radiobutton(question_frame, variable=self.var_q3,
                    value=5).grid(column=5, row=6)

        Label(question_frame,
              text="The dialogue as a whole feels natural").grid(column=0,
                                                                 row=7,
                                                                 sticky="W")
        Radiobutton(question_frame, variable=self.var_q4,
                    value=1).grid(column=1, row=7)
        Radiobutton(question_frame, variable=self.var_q4,
                    value=2).grid(column=2, row=7)
        Radiobutton(question_frame, variable=self.var_q4,
                    value=3).grid(column=3, row=7)
        Radiobutton(question_frame, variable=self.var_q4,
                    value=4).grid(column=4, row=7)
        Radiobutton(question_frame, variable=self.var_q4,
                    value=5).grid(column=5, row=7)

        #E1 = Entry(question_frame)

        ####    NEXT QUESTIONS BUTTON:
        button_next = Frame(self.interior, class_="Evaluation_3")
        button_next.pack(fill=X, anchor=N)

        Label(button_next, text="").pack(side='top', anchor='w')
        Label(
            button_next,
            text=
            "Please give your comment here.\nFor example, give the reason why do you think the reply question is not appropriate, \nincorrect grammar, not related to your answer, or why it does not feel natural.",
            justify=LEFT).pack(side='top', anchor='w')

        self.var_comment = StringVar()
        self.E1 = Entry(button_next, textvariable=self.var_comment)
        self.E1.pack(side='top', anchor='w', expand=YES, fill=X)
        Label(button_next, text="").pack()

        #button
        self._button_next = Button(button_next,
                                   text="Next Dialogue >>",
                                   command=self._on_click_next,
                                   width=50)
        self._button_next.pack()

        ####

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

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

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

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

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

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

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

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

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

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

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

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

        self.set_nick(my_nick)

    @property
    def topic(self):
        return

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

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

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

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

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

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

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

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

        self._write((content, tag))

    notification = notification_message

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

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

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

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

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

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

        self.user_message(self._my_nick, content)

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

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

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

        self._textarea.config(state=NORMAL)

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

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

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

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

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

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

        self._textarea.config(state=DISABLED)

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

    def _on_message_sent(self, event):

        if not self._entry.get():  # or not self.var_entry.get()
            showwarning('Empty answer', 'Please fill your anwer')
        else:
            #  update flag press enter
            global flag_press_enter
            global counter_enter_global

            if flag_press_enter == False:
                flag_press_enter = True
                #counter_enter += 1

            if flag_press_enter == True:
                if counter_enter_global < 2:

                    counter_enter_global += 1

                    # get the input from user
                    #print("var_entry:",self.var_entry.get())
                    message = self._entry.get()
                    # clear entry
                    self._entry.delete(0, END)

                    self.send(message)

                    if self._command:
                        self._command(
                            message)  # display user input to the chat window

                    if counter_enter_global > 1:
                        self._textarea.config(state=NORMAL)
                        self._textarea.insert(
                            END,
                            "\n[Thank you for your response. Continue to evaluate the Reply Question]"
                        )
                        self._textarea.config(state=DISABLED)

                    else:
                        ''' running the follow-up question generation '''

                        with open(input_path, 'w') as f:
                            f.write("%s\n" % message)

                        pp.preprocess_senna_input(input_path, senna_input_path)
                        rs.runSENNA(senna_input_file)

                        # getting semantic representation
                        sentenceList, dlines = fqg.create_SR(senna_input_path)

                        # generate the questions
                        listOfAllGeneratedQA = fqg.generate_questions(
                            sentenceList, dlines)
                        print(listOfAllGeneratedQA)

                        #reply_list = random.choice(listOfAllGeneratedQA[0])
                        reply = rs.ranking(listOfAllGeneratedQA)

                        if self._log is not None:
                            self._log.write("\nTemplate: %s" %
                                            listOfAllGeneratedQA)
                        #reply = reply_list[0]
                        print(reply)
                        self.user_message("Reply question", reply)

                else:
                    showinfo(
                        'Thank you',
                        'Thank you for your response. Please continue to evaluate the Reply Question'
                    )
                    self._entry.focus()

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

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

            self._entry_label["text"] = text
            self._entry_label.pack(side=LEFT, padx=(5, 5), before=self._entry)
        else:
            self._entry_label.pack_forget()

    def _on_click_next(self):
        global flag_press_enter
        global counter_enter_global
        maximum_counter = 10

        if flag_press_enter == True and self.var_q1.get(
        ) != 0 and self.var_q2.get() != 0 and self.var_q3.get(
        ) != 0 and self.var_q4.get() != 0:
            global counter_question_global

            if self._log is not None:
                self._log.write("\nDialogue number: %s" %
                                str(counter_question_global))

            # increase question counter
            counter_question_global += 1

            # write questionnaire's answers to log file
            if self._log is not None:
                self._log.write("\nQ1: %s" % self.var_q1.get())
                self._log.write("\nQ2: %s" % self.var_q2.get())
                self._log.write("\nQ3: %s" % self.var_q3.get())
                self._log.write("\nQ3: %s" % self.var_q4.get())
                self._log.write("\nComment: %s" % self.var_comment.get())

        #print ('debug: ',self.var_q1.get())
        if counter_question_global > maximum_counter:
            showinfo(
                'Finish',
                'Thank you for your participation! \nWe will now save your responses. \nPress OK to close the application.'
            )
            if OK:
                self._master.destroy()
                global flag_close
                flag_close = True
        elif self.var_q1.get() == 0 and flag_press_enter == True:
            showinfo('Rate the evaluation', 'Please rate all evaluations.')
        elif self.var_q2.get() == 0 and flag_press_enter == True:
            showinfo('Rate the evaluation', 'Please rate all evaluations.')
        elif self.var_q3.get() == 0 and flag_press_enter == True:
            showinfo('Rate the evaluation', 'Please rate all evaluations.')
        elif self.var_q4.get() == 0 and flag_press_enter == True:
            showinfo('Rate the evaluation', 'Please rate all evaluations.')
        else:
            # clear chat area
            self._textarea.config(state=NORMAL)
            self._textarea.delete('1.0', END)
            self._textarea.config(state=DISABLED)

            # fill with new starter's question
            with open(starter_questions) as f:
                dlines = f.read().splitlines(
                )  #reading a file without newlines
            starter = (random.choice(dlines))
            self.user_message("Question", starter)

            # update question counter
            counter_question.set(str(counter_question_global))

            # reset
            flag_press_enter = False
            counter_enter_global = 0
            self.var_q1.set(0)  # questionnaire 1
            self.var_q2.set(0)  # questionnaire 2
            self.var_q3.set(0)  # questionnaire 3
            self.var_q4.set(0)  # questionnaire 3
            self.E1.delete(0, END)  # clear comment
            self._entry.delete(0, END)  # clear entry message
예제 #11
0
class Participant(object):
    """
    Creates the input frame and stores the information regarding the
    participant
    """
    def __init__(self, parent, *args, **kwargs):
        """
        Initialize the input frame and call to inititialize the user
        interface
        """
        # Set the Tk as the parent
        self.parent = parent
        # Initialize the user interface
        self.initUI()

    def initUI(self):
        """
        Initializes the user interface

        Setting up the entry widgets for:
        - Experiment_ID
        - Participant Name
        - Session Day
        - Pupil Size
        - Practice
        - Stereo
        """
        # Set the title
        self.parent.title(EXP_NAME)

        # Create the label for Experiment_ID and set location
        label_id = Label(text='Participant ID:')
        label_id.place(x=20, y=20)

        # Check the DATA_DIR directory for previous participants
        # and choose the next Experiment_ID in line
        self.folders = listdir(DATA_DIR)
        # Initiate Tkinter's StringVar
        self.value_id = StringVar()
        # Set the default value
        self.value_id.set('001')
        # Going in reverse order of the participants' directories in
        # DATA_DIR, find the last participant's Experiment_ID and opt
        # for the next one in line
        for folder in reversed(self.folders):
            try:
                # Check if the value of the first 3 digits of the
                # directory name is greater than the default value
                if int(folder[:3]) >= int(self.value_id.get()):
                    # Get the next Experiment_ID in integer form and
                    # convert to string format
                    num = str(int(folder[:3]) + 1)
                    # Actions to perform in case scenarios for each
                    # of the possibilites of num_length
                    num_length = {3: num, 2: '0%s' % num, 1: '00%s' % num}
                    # Set the value accordingly to the StringVar,
                    # replacing the default
                    self.value_id.set(num_length[len(num)])
            # In case there are other folders in DATA_DIR, for which
            # the first 3 characters are not digits, we must cater
            # for when an exception is thrown up
            except ValueError:
                pass
        # Create the entry widget for Experiment_ID with the preset
        # value and state disabled
        self.input_id = Entry(self.parent,
                              width=5,
                              state=DISABLED,
                              textvariable=self.value_id)
        self.input_id.place(x=150, y=20)

        # Create the label for Participant Name and set location
        label_name = Label(text='Participant Name:')
        label_name.place(x=20, y=50)

        # Initiate Tkinter's StringVar
        self.value_name = StringVar()
        # Set the default value
        self.value_name.set('')
        # Create the entry for Participant Name and set location
        self.input_name = Entry(self.parent,
                                width=35,
                                textvariable=self.value_name)
        self.input_name.place(x=150, y=50)
        self.input_name.focus()

        # Create the label for Session Day and set location
        label_day = Label(text='Session Day:')
        label_day.place(x=20, y=80)

        # Create value holder for Session Day as IntVar and set default
        # value to 1
        self.value_day = IntVar()
        self.value_day.set(1)
        # Create the radiobuttons as required
        for day in range(1, TOTAL_SESSIONS + 1):
            input_day = Radiobutton(self.parent,
                                    text=str(day),
                                    variable=self.value_day,
                                    value=day)
            # Anchor them to the West (W)
            input_day.pack(anchor=W)
            # Choose location for the radiobuttons
            input_day.place(x=150, y=(50 + (day * 25)))

        # Create the label for Pupil Size and set location
        label_pupilsize = Label(text='Pupil Size:')
        label_pupilsize.place(x=20, y=140)

        self.value_pupilsize = StringVar()
        self.value_pupilsize.set('')
        # Create the MaxLengthEntry for Pupil Size and set location
        # The maximum length is set to 3 characters and a float must be
        # provided
        self.input_pupilsize = MaxLengthEntry(self.parent,
                                              width=5,
                                              maxlength=3,
                                              required_type=float)
        self.input_pupilsize.config(textvariable=self.value_pupilsize)
        self.input_pupilsize.place(x=150, y=140)

        # Create value folder for Practice as IntVar
        self.value_practice = IntVar()
        # Create the checkbutton for Practice and set location
        input_practice = Checkbutton(self.parent,
                                     text='Practice',
                                     variable=self.value_practice,
                                     onvalue=1,
                                     offvalue=0)
        input_practice.place(x=150, y=170)

        # Create value holder for Stereo as IntVar
        self.value_stereo = IntVar()
        # Create the checkbutton for Stereo and set location
        input_stereo = Checkbutton(self.parent,
                                   text='Stereo',
                                   variable=self.value_stereo,
                                   onvalue=1,
                                   offvalue=0)
        input_stereo.place(x=150, y=200)

        # Create the label for Previous Subjects and set location
        label_previous = Label(text='Previous Subjects:')
        label_previous.place(x=20, y=250)

        # Create the Listboc containing all the previous participants
        self.input_previous = Listbox(self.parent, width=35, height=10)
        for identifier in self.folders:
            self.input_previous.insert(END, identifier)
        self.input_previous.place(x=150, y=250)
        self.input_previous.bind('<<ListboxSelect>>', self.__select_previous)

        # Create the submit button, give command upon pressing and set
        # location
        submit = Button(text='Submit', width=47, command=self.gather_input)
        submit.pack(padx=8, pady=8)
        submit.place(x=20, y=425)

    def __select_previous(self, event):
        """
        Handle scenario where user selects one of the previous participants
        """
        # Collect from previous subjects, if it was chosen
        self.previous = self.input_previous.curselection()
        if self.previous:
            self.previous = self.folders[int(self.previous[0])]
            with open(join(DATA_DIR, self.previous, 'data.json')) as f:
                data = load(f)
                # Set the value for participant ID
                self.value_id.set(data['ID'])
                # Set the value for name and disable the user from making
                # any more changes
                self.value_name.set(data['Name'])
                self.input_name.config(state=DISABLED)
                # Set the value for pupilsize and disable the user from
                # making any more changes
                self.value_pupilsize.set(data['Pupil Size'])
                self.input_pupilsize.config(state=DISABLED)

    def gather_input(self):
        """
        Gather the input from the Tkinter window and store it as class
        variables of the Participant class

        This module will also create a folder for the participant if
        it does not exist already in DATA_DIR
        NOTE: DATA_DIR is set in settings.py
        """
        # Collect all the values input and convert to their appropriate
        # types
        self.subject_id = self.input_id.get()
        self.name = self.input_name.get().title()
        self.day = int(self.value_day.get())
        try:
            self.pupilsize = float(self.input_pupilsize.get())
        except ValueError:
            pass
        self.practice = bool(self.value_practice.get())
        self.stereo = bool(self.value_stereo.get())

        # Destroy the Tkinter window
        self.parent.destroy()

        # Put together the directory name and path
        self.subject_dir = '%s_%s' % (self.subject_id,
                                      self.name.replace(' ', ''))
        self.subject_dir = join(DATA_DIR, self.subject_dir)
        # If the directory for the participant does not exist, create it
        if not exists(self.subject_dir):
            makedirs(self.subject_dir)
예제 #12
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()
예제 #13
0
class ROIApp(object):

    def __init__(self, source_dir):
        self.state = "Selecting"

        self.image_types = ["ppm", "jpg", "jpeg", "png", "bmp"]  # Add more
        self.source_dir = source_dir
        self.gt_filename = os.path.join(self.source_dir, "gt.txt")
        images = self.get_images()
        self.image_fullpaths = (
            os.path.join(self.source_dir, image_filename)
            for image_filename in images)
        self.current_image_fullpath = None
        self.gt_file = open(self.gt_filename, 'a')
        self.gt_writer = csv.writer(self.gt_file, delimiter=";")

        self.root = Tk()
        self.root.bind("<Escape>", lambda e: self.quit())
        self.root.bind("<KP_Enter>", self.on_kp_enter)
        self.root.bind("<Return>", self.on_kp_enter)
        self.root.wm_title("ROI Tool")
        self.root.protocol("WM_DELETE_WINDOW", self.quit)  # Confirm?

        # Frame for the input field and buttons
        self.input_frame = Frame(self.root)
        self.input_frame.pack(side="top")

        self.label = Label(self.input_frame, text="Class:")
        self.label.pack(side="left")
        self.entry_field = Entry(self.input_frame)
        self.entry_field.pack(side="left")

        self.image_label = Label(self.root)
        self.image_label.pack(side="bottom")
        self.image_label.bind("<ButtonPress-1>", self.on_button_press)
        self.image_label.bind("<ButtonRelease-1>", self.on_button_release)

        self.image = None
        self.imagetk = None
        self.draw = None

        self.ref_pts = []
        self.ref_start = None
        self.ref_pts_iter = None
        self.current_ref_pt = None
        self.gt_rows = []

        try:
            self.next_image()
        except StopIteration:
            print("No images were found (extensions %s) "
                  "or all the images found were already parsed, check file "
                  "%s" % (", ".join(self.image_types), self.gt_filename))
            self.quit()
            sys.exit(1)
        self.show_frame()

    def quit(self):
        self.gt_file.close()
        self.root.quit()

    def ask_for_next_category(self):
        """Ask for next category if another ref point exists,
        else move onto next image"""
        try:
            self.current_ref_pt = self.ref_pts_iter.next()
            self.draw.rectangle(self.current_ref_pt, outline="red")
            self.entry_field.select_range(0, "end")
            self.entry_field.focus()
        except StopIteration:
            self.state = "Selecting"
            try:
                self.next_image()
            except StopIteration:
                print(
                    "Done, regions of interest written in %s" %
                    self.gt_filename)
                self.quit()

    def on_kp_enter(self, event):
        if self.state == "Categorizing":
            category = self.entry_field.get()
            image_path = self.current_image_fullpath.split("/")[-1]
            data = ((image_path,) + self.current_ref_pt[0] +
                    self.current_ref_pt[1] + (category,))
            self.gt_rows.append(data)
            self.draw.rectangle(self.current_ref_pt, outline="blue")
            self.ask_for_next_category()
        else:
            self.state = "Categorizing"
            self.ref_pts_iter = iter(self.ref_pts)
            self.ref_pts = []
            self.ask_for_next_category()

    def get_images(self):
        try:
            gt_file = open(self.gt_filename, 'r')
            reader = csv.reader(gt_file, delimiter=";")
            already_parsed = [row[0] for row in reader]
        except IOError:
            already_parsed = []
        return [filename for filename in os.listdir(self.source_dir) if
                (filename.split(".")[-1] in self.image_types and
                 filename not in already_parsed)]

    def next_image(self):
        self.gt_writer.writerows(self.gt_rows)
        self.gt_rows = []
        self.current_image_fullpath = self.image_fullpaths.next()
        self.image = Image.open(self.current_image_fullpath)
        self.draw = ImageDraw.Draw(self.image)

    def show_frame(self):
        self.imagetk = ImageTk.PhotoImage(image=self.image)
        self.image_label.configure(image=self.imagetk)
        self.image_label.after(10, self.show_frame)

    def on_button_press(self, event):
        if self.state == "Selecting":
            self.ref_start = (event.x, event.y)

    def on_button_release(self, event):
        if self.state == "Selecting":
            # Make sure ROI doesn't exceed pixture coordinates and that
            # the corners go from top left to bottom right
            ref_end = (event.x, event.y)
            ref_pt = self.top_left_to_bottom_right(ref_end)
            self.ref_pts.append(ref_pt)

            # Draw rectangle around ROI
            self.draw.rectangle(
                self.ref_pts[-1],
                outline="green")

    def top_left_to_bottom_right(self, ref_end):
        """Returns the tuple:
            (top_left, bottom_right) where top_left and bottom_right
            are coordinate tuples"""
        x1 = max(0, min(self.ref_start[0], ref_end[0]))
        x2 = min(max(self.ref_start[0], ref_end[0]), self.image.size[0])
        y1 = max(0, min(self.ref_start[1], ref_end[1]))
        y2 = min(max(self.ref_start[1], ref_end[1]), self.image.size[1])
        return ((x1, y1), (x2, y2))
예제 #14
0
파일: UI.py 프로젝트: siweisun/clusterfk
class StatePopup(object):
    def __init__(self, master, default_value, state_probs):
        top = self.top = Toplevel(master.canvas)
        self.master = master

        self.l = Label(top, text="New State")
        self.l.grid(row=0, column=0, columnspan=2)

        self.lb = Listbox(
            top
        )  # OptionMenu(top, Tkinter.StringVar().set(self.states[-1]), *self.states)
        self.lb.insert("end", "0")
        for i, (state,
                color) in enumerate(self.master.trail.colorlist.items()):
            str = ",".join(["{:x}".format(x) for x in state])
            self.lb.insert("end", str)
            self.lb.itemconfig(i + 1, {"bg": color})
        self.lb.grid(row=1, column=1, padx=MARGIN_LR / 2, pady=MARGIN_TB)
        self.lb.config(height=5, width=8)
        self.lb.bind(
            "<Double-Button-1>",
            lambda x: self.set_text(self.lb.get(self.lb.curselection())))

        self.e = Entry(top)
        self.e.insert(0, default_value)
        self.e.bind("<Control-KeyRelease-a>", lambda x: self.select_all())
        self.e.grid(row=1,
                    column=0,
                    sticky=N,
                    padx=MARGIN_LR / 2,
                    pady=MARGIN_TB)
        self.e.select_range(0, 'end')
        self.e.icursor('end')
        self.e.focus()

        self.b = Button(top, text='Ok', command=self.check_cleanup)
        self.top.protocol("WM_DELETE_WINDOW", self.close)
        self.b.grid(row=3, column=0, columnspan=2)

        self.l2 = Label(top, text="Probabilities")
        self.l2.grid(row=4, column=0, columnspan=2)
        for i, x in enumerate(state_probs):
            # if x > 0:
            #    l = Label(top, text=hex(i)[2:] + ":" + str(x))
            #    l.pack()
            pass

        self.top.bind("<Return>", lambda x: self.check_cleanup())
        self.top.bind("<Escape>", lambda x: self.close())
        self.value = None
        self.top.wait_visibility()
        # stop interaction in other gui
        self.top.grab_set()

    def set_text(self, text):
        self.e.delete(0, 'end')
        self.e.insert(0, text)

    def select_all(event):
        event.e.select_range(0, 'end')
        # move cursor to the end
        event.e.icursor('end')
        return 'break'

    def check_cleanup(self):
        newstate = self.e.get()
        if newstate == "":
            self.value = range(
                0, 2**(self.master.trail.statebitsize /
                       self.master.trail.statesize))
        elif newstate == "*":
            self.value = range(
                1, 2**(self.master.trail.statebitsize /
                       self.master.trail.statesize))
        else:
            try:
                state = []
                for x in newstate.split(","):
                    x = x.strip()
                    x = int(x, 16)
                    assert x < 2**(self.master.trail.statebitsize /
                                   self.master.trail.statesize)
                    state.append(x)
                assert len(state) > 0
                self.value = state
            except Exception as e:
                print "Exception: " + str(e)
                self.value = None
                return

        self.close()

    def close(self):
        self.top.grab_release()
        self.top.destroy()
예제 #15
0
  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()

예제 #16
0
class MainWindow:
    def __init__(self):
        self.root = Tk()
        self.input_bundle = Bundle()
        self.stamp_bundle = Bundle()
        self.controllers = []
        self.main_frame = None
        self.state_label = None
        self.state_label_var = None
        self.state_indicator = None
        self.state_indicator_var = None
        self.success_button = None
        self.failed_button = None
        self.sn_input = None
        self.title_list = []

        self.state_code = Setting.RESULT_OK
        self.mark = 0
        self.listener = MainListener(self)
        self.context = Context(self.input_bundle, self.stamp_bundle, self.listener)
        self.main()

    def main(self):
        self.initialize()
        self.context.init_controller(self.controllers)
        self.state_label_var = StringVar()
        self.state_indicator_var = StringVar()
        self.title = u"产线工具"
        self.label_frame_title = u"产线测试工具客户端"
        self.root.title(self.title)
        self.root.geometry("800x260")
        self.label_frame = LabelFrame(self.root, text=self.label_frame_title)
        self.label_frame.pack(fill="both", expand="yes")
        self.main_frame = Frame(self.label_frame)
        self.main_frame.pack()
        self.state_label_var.set(u"准备Smt测试")
        self.state_label = Label(
            self.main_frame, textvariable=self.state_label_var, font=("Arial", 12), width=40, height=7, bg="#00BFFF"
        )
        self.state_label.pack(side=LEFT)
        self.state_indicator_var.set(u"未测试")
        self.state_indicator = Label(
            self.main_frame, textvariable=self.state_indicator_var, font=("Arial", 12), width=40, height=7, bg="#00BFFF"
        )
        self.state_indicator.pack(side=LEFT)
        self.control_frame = LabelFrame(self.label_frame)
        self.control_frame.pack(side=BOTTOM, fill="both", expand="yes")
        self.success_button = Button(
            self.control_frame, text=u"成功", font=("Arial", 12), width=15, height=3, command=self.on_success_button
        )
        self.failed_button = Button(
            self.control_frame, text=u"失败", font=("Arial", 12), width=15, height=3, command=self.on_failed_button
        )
        self.success_button.pack(side=LEFT)
        self.failed_button.pack(side=RIGHT)
        self.failed_button["state"] = DISABLED
        self.sn_input = Entry(self.control_frame, width=50, font=Font(size=42))
        self.sn_input.pack()
        self.disable_buttons()
        self.sn_input.bind("<KeyRelease-Return>", self.on_sn_input)
        self.root.resizable(width=False, height=False)
        if Setting.DEBUG:
            self.label_text("Debug!!!")

    def on_sn_input(self, event):
        self.input_bundle.params[Setting.ID] = self.sn_input.get()
        print ("sn %s" % self.sn_input.get())
        self.start_run()

    def loop(self):
        print ("mainloop")
        self.sn_input.focus()
        self.root.mainloop()

    def initialize(self):
        # _rom_controller = RomController(0, stamp_bundle, listener)
        # controllers.append(_rom_controller)
        # title_list.append(u'rom烧写')
        _sn_controller = SnController(1, self.stamp_bundle, self.listener)
        self.controllers.append(_sn_controller)
        self.title_list.append(u"Sn烧录")
        _adb_controller = AdbController(2, self.stamp_bundle, self.listener)
        self.controllers.append(_adb_controller)
        self.title_list.append(u"Smt测试")
        # _data_controller = DataController(4, stamp_bundle, listener)
        # controllers.append(_data_controller)
        # title_list.append(u'数据保存')
        # _adjust_controller = AdjustController(5, stamp_bundle, listener)
        # controllers.append(_adjust_controller)
        # title_list.append(u'wifi校准')
        # _backup_controller = BackupController(6, stamp_bundle, listener)
        # controllers.append(_backup_controller)
        # title_list.append(u'it备份')
        # _book_set_controller = BookSetController(7, stamp_bundle, listener)
        # controllers.append(_book_set_controller)
        # title_list.append(u'预置书籍')
        # _reset_controller = ResetController(8, stamp_bundle, listener)
        # controllers.append(_reset_controller)
        # title_list.append(u'重置系统')
        # _print_controller = PrintController(9, stamp_bundle, listener)
        # controllers.append(_print_controller)
        # title_list.append(u'打印标签')
        # _weight_controller = WeightController(10, stamp_bundle, listener)
        # controllers.append(_weight_controller)
        # title_list.append(u'彩盒称重')

    def label_normal(self, text=None):
        self.state_label["background"] = "#00BFFF"
        self.state_indicator["background"] = "#00BFFF"
        if text is not None:
            self.label_failed(str(text))

    def label_success(self, text=None):
        self.state_label["background"] = "#2E8B57"
        self.state_indicator["background"] = "#2E8B57"
        if text is not None:
            self.label_failed(str(text))

    def label_failed(self, text=None):
        self.state_label["background"] = "#DC143C"
        self.state_indicator["background"] = "#DC143C"
        if text is not None:
            self.label_failed(str(text))

    def label_text(self, text):
        self.state_label_var.set(text)
        self.root.update()

    def status_text(self, text):
        self.state_indicator_var.set(text)
        if text.endswith("Pass"):
            self.label_success()
        elif text.endswith("Failed"):
            self.label_failed()
        else:
            self.label_normal()

    def _start_run(self):
        print ("Running")
        self.label_normal()
        self.context.run()

    def disable_buttons(self):
        self.success_button["state"] = DISABLED
        self.failed_button["state"] = DISABLED

    def enable_buttons(self):
        self.success_button["state"] = NORMAL
        self.failed_button["state"] = NORMAL

    def start_run(self):
        print ("wait running")
        self.disable_buttons()
        self.root.after(300, self._start_run)

    def on_failed_button(self):
        self.disable_buttons()
        self._retval = self.context.report_failure()
        if self._retval == Setting.RESULT_FAILED:
            self.context.clear()
        self.state_indicator_var.set(u"失败")
        self.state_label["background"] = "#DC143C"
        self.state_indicator["background"] = "#DC143C"
        self.start_run()

    def on_success_button(self):
        self.disable_buttons()

        self.state_label["background"] = "#DC143C"
        self.state_indicator["background"] = "#DC143C"
        self.start_run()
예제 #17
0
scroll = Scrollbar(root)
scroll.pack(side=RIGHT, fill=Y, expand=0)

text = Text(root, yscrollcommand=scroll.set)
text.config(state=DISABLED, wrap=WORD)
text.pack(fill=BOTH, expand=1)

hyper = HyperlinkManager(text)

post_button = Button(root, text="Post", command=postThreader)
post_button.pack(side=RIGHT, fill=BOTH, expand=0)

Label(root, textvariable=TEXT).pack(side=RIGHT)

entry = Entry(root)
entry.focus()
entry.pack(fill=X, expand=1, side=RIGHT)

short = shortner.Shorten('AIzaSyCup5SNezq62uKQQQHQoFTmqKAGnJDoq-A', entry)

scroll.config(command=text.yview)

menu = Menu(root)
acctMenu = Menu(menu, tearoff=0)
menu.add_command(label="Update", command=oneShotUpdate)
menu.add_command(label="Console", command=showConsole)
menu.add_command(label="Search", command=hashThreader)
menu.add_command(label="Delete last tweet", command=delThreader)
menu.add_command(label="Shorten link", command=shortThreader)
menu.add_cascade(label="Accounts", menu=acctMenu)
menu.add_separator()
예제 #18
0
    ''' execute this fucntion when button is clicked '''
    lbl2 = Label(window, text="Clicked!",
                 font=("Arial Bold", 12))  # wll show the new text
    print("button 1")
    lbl2.grid(column=0, row=1)  # necessary to set the location of the
    # lbl2.configure(text="Button was clicked !!")


btn = Button(window, text="Click Me", bg="orange", fg="red",
             command=clicked)  # with colros annd fucntion
btn.grid(column=1, row=0)  # set the location
''' imput text '''
txt = Entry(window, width=10)
txt.grid(column=0, row=2)
input_text = txt.get()
txt.focus()  # will focus the user on this line


# txt = Entry(window,width=10, state='disabled') # does not allow user to enter the text
# use the new button to show the text
def show_text():
    ''' show this text when the button is clicked'''
    lbl3 = Label(window, text="input text", font=("Arial", 12))
    lbl3.grid(column=2, row=2)


btn2 = Button(window, text="show text", bg="blue", fg="red", command=show_text)
btn2.grid(column=1, row=2)
''' combox '''

combo = Combobox(window)
예제 #19
0
    def __init__(self):
        self.error = True
        window = Tk()
        window.title("Tub_Calculator")
        window.configure(background='orange')

        self.string = StringVar()
        entry = Entry(window,
                      textvariable=self.string,
                      font="Helvetica 17 bold")
        entry.grid(row=0, column=0, columnspan=6)
        entry.bind('<KeyPress>', self.keyPress)
        entry.focus()

        values = [
            "7", "8", "9", "/", "Clear", "<-", "4", "5", "6", "*", "(", ")",
            "1", "2", "3", "-", "=", "0", ".", "%", "+"
        ]

        i = 0
        row = 1
        col = 0
        for txt in values:
            padx = 10
            pady = 10

            if (i == 6):
                row = 2
                col = 0
            if (i == 12):
                row = 3
                col = 0
            if (i == 17):
                col = 0
                row = 4

            if (txt == "="):
                btn = Button(window,
                             height=1,
                             width=2,
                             padx=23,
                             pady=23,
                             text=txt,
                             command=lambda txt=txt: self.equals())
                btn.grid(row=row,
                         column=col,
                         columnspan=2,
                         rowspan=2,
                         padx=1,
                         pady=1)
            elif (txt == "Clear"):
                btn = Button(window,
                             height=1,
                             width=2,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.clearTxt())
                btn.grid(row=row, column=col, padx=1, pady=1)
            elif (txt == "<-"):
                btn = Button(window,
                             height=1,
                             width=2,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.delete())
                btn.grid(row=row, column=col, padx=1, pady=1)
            else:
                btn = Button(window,
                             height=1,
                             width=2,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.addChar(txt))
                btn.grid(row=row, column=col, padx=1, pady=1)

            col = col + 1
            i = i + 1

        window.mainloop()
    def __init__(self):
        window = Tk()
        window.title('Scientific Calculator')
        window.configure(background="white")
        self.string = StringVar()
        entry = Entry(window, textvariable=self.string)
        entry.grid(row=0, column=0, columnspan=6)
        entry.configure(background="white")
        entry.focus()

        values = [
            "7", "8", "9", "/", "%", "clear", "AC", "4", "5", "6", "*", "(",
            ")", "**", "1", "2", "3", "-", "=", ",", "0", ".", "min", "+",
            "sin", "asin", "cos", "acos", "tan()", "pow", "log10", "max",
            "abs", "floor", "pi", "e", "log", "ceil", "degrees", "radians"
        ]
        text = 1
        i = 0
        row = 1
        col = 0
        for txt in values:
            padx = 10
            pady = 10
            if (i == 7):
                row = 2
                col = 0
            if (i == 14):
                row = 3
                col = 0
            if (i == 19):
                row = 4
                col = 0
            if (i == 26):
                row = 5
                col = 0
            if (i == 33):
                row = 6
                col = 0
            if (txt == '='):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=70,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.equals())
                btn.grid(row=row, column=col, columnspan=3, padx=2, pady=2)
                btn.configure(background="yellow")

            elif (txt == 'clear'):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.delete())
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="grey")
            elif (txt == 'AC'):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.clearall())
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="red")
            else:
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.addChar(txt))
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="cyan")

            col = col + 1
            i = i + 1
        window.mainloop()
예제 #21
0
class SearchBox(Frame):
    def __init__(self, master, entry_width=30, entry_font=None, entry_background="white", entry_highlightthickness=1, button_text="Search", button_ipadx=10, button_background="#009688", button_foreground="white", button_font=None, opacity=0.8, placeholder=None, placeholder_font=None, placeholder_color="grey", spacing=3, command=None):
        Frame.__init__(self, master)
        
        self._command = command

        self.entry = Entry(self, width=entry_width, background=entry_background, highlightcolor=button_background, highlightthickness=entry_highlightthickness)
        self.entry.pack(side=LEFT, fill=BOTH, ipady=1, padx=(0,spacing))
        
        if entry_font:
            self.entry.configure(font=entry_font)

        if placeholder:
            add_placeholder_to(self.entry, placeholder, color=placeholder_color, font=placeholder_font)

        self.entry.bind("<Escape>", lambda event: self.entry.nametowidget(".").focus())
        self.entry.bind("<Return>", self._on_execute_command)

        opacity = float(opacity)

        if button_background.startswith("#"):
            r,g,b = hex2rgb(button_background)
        else:
            # Color name
            r,g,b = master.winfo_rgb(button_background)

        r = int(opacity*r)
        g = int(opacity*g)
        b = int(opacity*b)

        if r <= 255 and g <= 255 and b <=255:
            self._button_activebackground = '#%02x%02x%02x' % (r,g,b)
        else:
            self._button_activebackground = '#%04x%04x%04x' % (r,g,b)

        self._button_background = button_background

        self.button_label = Label(self, text=button_text, background=button_background, foreground=button_foreground, font=button_font)
        if entry_font:
            self.button_label.configure(font=button_font)
            
        self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx)
        
        self.button_label.bind("<Enter>", self._state_active)
        self.button_label.bind("<Leave>", self._state_normal)

        self.button_label.bind("<ButtonRelease-1>", self._on_execute_command)

    def get_text(self):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            if entry.placeholder_state.contains_placeholder:
                return ""
            else:
                return entry.get()
        else:
            return entry.get()
        
    def set_text(self, text):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            entry.placeholder_state.contains_placeholder = False

        entry.delete(0, END)
        entry.insert(0, text)
        
    def clear(self):
        self.entry_var.set("")
        
    def focus(self):
        self.entry.focus()

    def _on_execute_command(self, event):
        text = self.get_text()
        self._command(text)

    def _state_normal(self, event):
        self.button_label.configure(background=self._button_background)

    def _state_active(self, event):
        self.button_label.configure(background=self._button_activebackground)
예제 #22
0
class Participant(object):
    """
    Creates the input frame and stores the information regarding the
    participant
    """
    def __init__(self, parent, *args, **kwargs):
        """
        Initialize the input frame and call to inititialize the user
        interface
        """
        # Set the Tk as the parent
        self.parent = parent
        # Initialize the user interface
        self.initUI()

    def initUI(self):
        """
        Initializes the user interface

        Setting up the entry widgets for:
        - Experiment_ID
        - Participant Name
        - Session Day
        - Pupil Size
        - Practice
        - Stereo
        """
        # Set the title
        self.parent.title(EXP_NAME)

        # Create the label for Experiment_ID and set location
        label_id = Label(text='Participant ID:')
        label_id.place(x=20, y=20)

        # Check the DATA_DIR directory for previous participants
        # and choose the next Experiment_ID in line
        self.folders = listdir(DATA_DIR)
        # Initiate Tkinter's StringVar
        self.value_id = StringVar()
        # Set the default value
        self.value_id.set('001')
        # Going in reverse order of the participants' directories in
        # DATA_DIR, find the last participant's Experiment_ID and opt
        # for the next one in line
        for folder in reversed(self.folders):
            try:
                # Check if the value of the first 3 digits of the
                # directory name is greater than the default value
                if int(folder[:3]) >= int(self.value_id.get()):
                    # Get the next Experiment_ID in integer form and
                    # convert to string format
                    num = str(int(folder[:3]) + 1)
                    # Actions to perform in case scenarios for each
                    # of the possibilites of num_length
                    num_length = {
                                  3: num,
                                  2: '0%s' % num,
                                  1: '00%s' % num
                    }
                    # Set the value accordingly to the StringVar,
                    # replacing the default
                    self.value_id.set(num_length[len(num)])
            # In case there are other folders in DATA_DIR, for which
            # the first 3 characters are not digits, we must cater
            # for when an exception is thrown up
            except ValueError:
                pass
        # Create the entry widget for Experiment_ID with the preset
        # value and state disabled
        self.input_id = Entry(self.parent, width=5, state=DISABLED,
                              textvariable=self.value_id)
        self.input_id.place(x=150, y=20)

        # Create the label for Participant Name and set location
        label_name = Label(text='Participant Name:')
        label_name.place(x=20, y=50)

        # Initiate Tkinter's StringVar
        self.value_name = StringVar()
        # Set the default value
        self.value_name.set('')
        # Create the entry for Participant Name and set location
        self.input_name = Entry(self.parent, width=35,
                                textvariable=self.value_name)
        self.input_name.place(x=150, y=50)
        self.input_name.focus()

        # Create the label for Session Day and set location
        label_day = Label(text='Session Day:')
        label_day.place(x=20, y=80)

        # Create value holder for Session Day as IntVar and set default
        # value to 1
        self.value_day = IntVar()
        self.value_day.set(1)
        # Create the radiobuttons as required
        for day in range(1, TOTAL_SESSIONS + 1):
            input_day = Radiobutton(self.parent, text=str(day),
                                    variable=self.value_day, value=day)
            # Anchor them to the West (W)
            input_day.pack(anchor=W)
            # Choose location for the radiobuttons
            input_day.place(x=150, y=(50 + (day * 25)))

        # Create the label for Pupil Size and set location
        label_pupilsize = Label(text='Pupil Size:')
        label_pupilsize.place(x=20, y=140)

        self.value_pupilsize = StringVar()
        self.value_pupilsize.set('')
        # Create the MaxLengthEntry for Pupil Size and set location
        # The maximum length is set to 3 characters and a float must be
        # provided
        self.input_pupilsize = MaxLengthEntry(self.parent, width=5,
                                              maxlength=3,
                                              required_type=float)
        self.input_pupilsize.config(textvariable=self.value_pupilsize)
        self.input_pupilsize.place(x=150, y=140)

        # Create value folder for Practice as IntVar
        self.value_practice = IntVar()
        # Create the checkbutton for Practice and set location
        input_practice = Checkbutton(self.parent, text='Practice',
                                     variable=self.value_practice, onvalue=1,
                                     offvalue=0)
        input_practice.place(x=150, y=170)

        # Create value holder for Stereo as IntVar
        self.value_stereo = IntVar()
        # Create the checkbutton for Stereo and set location
        input_stereo = Checkbutton(self.parent, text='Stereo',
                                   variable=self.value_stereo, onvalue=1,
                                   offvalue=0)
        input_stereo.place(x=150, y=200)

        # Create the label for Previous Subjects and set location
        label_previous = Label(text='Previous Subjects:')
        label_previous.place(x=20, y=250)

        # Create the Listboc containing all the previous participants
        self.input_previous = Listbox(self.parent, width=35, height=10)
        for identifier in self.folders:
            self.input_previous.insert(END, identifier)
        self.input_previous.place(x=150, y=250)
        self.input_previous.bind('<<ListboxSelect>>', self.__select_previous)

        # Create the submit button, give command upon pressing and set
        # location
        submit = Button(text='Submit', width=47, command=self.gather_input)
        submit.pack(padx=8, pady=8)
        submit.place(x=20, y=425)

    def __select_previous(self, event):
        """
        Handle scenario where user selects one of the previous participants
        """
        # Collect from previous subjects, if it was chosen
        self.previous = self.input_previous.curselection()
        if self.previous:
            self.previous = self.folders[int(self.previous[0])]
            with open(join(DATA_DIR, self.previous, 'data.json')) as f:
                data = load(f)
                # Set the value for participant ID
                self.value_id.set(data['ID'])
                # Set the value for name and disable the user from making
                # any more changes
                self.value_name.set(data['Name'])
                self.input_name.config(state=DISABLED)
                # Set the value for pupilsize and disable the user from
                # making any more changes
                self.value_pupilsize.set(data['Pupil Size'])
                self.input_pupilsize.config(state=DISABLED)

    def gather_input(self):
        """
        Gather the input from the Tkinter window and store it as class
        variables of the Participant class

        This module will also create a folder for the participant if
        it does not exist already in DATA_DIR
        NOTE: DATA_DIR is set in settings.py
        """
        # Collect all the values input and convert to their appropriate
        # types
        self.subject_id = self.input_id.get()
        self.name = self.input_name.get().title()
        self.day = int(self.value_day.get())
        try:
            self.pupilsize = float(self.input_pupilsize.get())
        except ValueError:
            pass
        self.practice = bool(self.value_practice.get())
        self.stereo = bool(self.value_stereo.get())

        # Destroy the Tkinter window
        self.parent.destroy()

        # Put together the directory name and path
        self.subject_dir = '%s_%s' % (self.subject_id,
                                      self.name.replace(' ', ''))
        self.subject_dir = join(DATA_DIR, self.subject_dir)
        # If the directory for the participant does not exist, create it
        if not exists(self.subject_dir):
            makedirs(self.subject_dir)
예제 #23
0
class SearchBox(Frame):
    def __init__(self,
                 master,
                 entry_width=30,
                 entry_font=None,
                 entry_background="white",
                 entry_highlightthickness=1,
                 button_text="Search",
                 button_ipadx=10,
                 button_background="#009688",
                 button_foreground="white",
                 button_font=None,
                 opacity=0.8,
                 placeholder=None,
                 placeholder_font=None,
                 placeholder_color="grey",
                 spacing=3,
                 command=None):
        Frame.__init__(self, master)

        self._command = command

        self.entry = Entry(self,
                           width=entry_width,
                           background=entry_background,
                           highlightcolor=button_background,
                           highlightthickness=entry_highlightthickness)
        self.entry.pack(side=LEFT, fill=BOTH, ipady=1, padx=(0, spacing))

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

        if placeholder:
            add_placeholder_to(self.entry,
                               placeholder,
                               color=placeholder_color,
                               font=placeholder_font)

        self.entry.bind("<Escape>",
                        lambda event: self.entry.nametowidget(".").focus())
        self.entry.bind("<Return>", self._on_execute_command)

        opacity = float(opacity)

        if button_background.startswith("#"):
            r, g, b = hex2rgb(button_background)
        else:
            # Color name
            r, g, b = master.winfo_rgb(button_background)

        r = int(opacity * r)
        g = int(opacity * g)
        b = int(opacity * b)

        if r <= 255 and g <= 255 and b <= 255:
            self._button_activebackground = '#%02x%02x%02x' % (r, g, b)
        else:
            self._button_activebackground = '#%04x%04x%04x' % (r, g, b)

        self._button_background = button_background

        self.button_label = Label(self,
                                  text=button_text,
                                  background=button_background,
                                  foreground=button_foreground,
                                  font=button_font)
        if entry_font:
            self.button_label.configure(font=button_font)

        self.button_label.pack(side=LEFT, fill=Y, ipadx=button_ipadx)

        self.button_label.bind("<Enter>", self._state_active)
        self.button_label.bind("<Leave>", self._state_normal)

        self.button_label.bind("<ButtonRelease-1>", self._on_execute_command)

    def get_text(self):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            if entry.placeholder_state.contains_placeholder:
                return ""
            else:
                return entry.get()
        else:
            return entry.get()

    def set_text(self, text):
        entry = self.entry
        if hasattr(entry, "placeholder_state"):
            entry.placeholder_state.contains_placeholder = False

        entry.delete(0, END)
        entry.insert(0, text)

    def clear(self):
        self.entry_var.set("")

    def focus(self):
        self.entry.focus()

    def _on_execute_command(self, event):
        text = self.get_text()
        self._command(text)

    def _state_normal(self, event):
        self.button_label.configure(background=self._button_background)

    def _state_active(self, event):
        self.button_label.configure(background=self._button_activebackground)
예제 #24
0
class Words:
    def __init__(self, master):
        self.master = master
        master.title("Word Finder")

        letterCheck = master.register(self.CheckLetterEntry)
        wordLenCheck = master.register(self.CheckWordLenEntry)

        self.entryVariable = StringVar()
        self.entry = Entry(master,
                           textvariable=self.entryVariable,
                           validate='focusout',
                           validatecommand=(letterCheck, '%P'))
        self.entry.grid(column=0,
                        row=0,
                        columnspan=2,
                        sticky='EW',
                        padx=10,
                        pady=20,
                        ipadx=10,
                        ipady=10)
        #self.entry.bind("<Return>", self.OnButtonClick)
        self.entryVariable.set(u"Letters")

        wordLenLabel = Label(master,
                             text="Word Length",
                             anchor="e",
                             justify="right",
                             padx=10,
                             pady=20)
        wordLenLabel.grid(column=0, row=1, sticky='E')

        self.wordLenVariable = StringVar()
        self.wordLenEntry = Entry(master,
                                  textvariable=self.wordLenVariable,
                                  validate='focusout',
                                  validatecommand=(wordLenCheck, '%P'))
        self.wordLenEntry.grid(column=1,
                               row=1,
                               padx=10,
                               pady=10,
                               ipadx=10,
                               ipady=10)
        self.wordLenVariable.set("0")

        button = Button(master,
                        text=u"Find Words!",
                        command=self.OnButtonClick,
                        pady=10,
                        fg="#383a39",
                        bg="#a1dbcd")
        button.grid(column=0, row=2, columnspan=2, pady=10)
        #button['state'] = "disabled"

        self.canvas = Canvas(master, width=300, height=50)
        self.canvas.grid(column=0, row=4, columnspan=2)

        self.resultsText = Text(master, state="disabled")
        self.resultsText.grid(column=0, row=3, columnspan=2)

        master.grid_columnconfigure(0, weight=1)

        #	master.resizable(False,True)
        master.update()
        #master.geometry(self.geometry())
        #self.entry.focus_set()
        self.entry.focus()
        #self.entry.selection_range(0, Tkinter.END)

        #self.entryVariable.trace("w", validateFields)
        #self.giflist = []
        #self.giflist.append(PhotoImage('loadingdot1.gif'))
        #self.giflist.append(PhotoImage('loadingdot2.gif'))
        #self.giflist.append(PhotoImage('loadingdot3.gif'))

        self.timer_id = None

    def draw_one_frame(self, picNbr=0):
        giflist = []
        giflist.append(PhotoImage(file='loadingdot1.gif'))
        giflist.append(PhotoImage(file='loadingdot2.gif'))
        giflist.append(PhotoImage(file='loadingdot3.gif'))
        #picNum = picNbr % (len(giflist))
        gif = giflist[picNbr]
        self.canvas.create_image(gif.width() // 2,
                                 gif.height() // 2,
                                 image=gif)

    def start_loading(self, currFrame):
        if currFrame > 2: currFrame = 0
        self.draw_one_frame(currFrame)
        currFrame = currFrame + 1
        root.update_idletasks()
        self.stop_id = root.after(100, self.start_loading(currFrame))

    def stop_loading(self):
        root.after_cancel(self.stop_id)
        self.canvas.delete(ALL)

    #def CheckLetterEntry(self, d, i, P, s, S, v, V, W):
    def CheckLetterEntry(self, new_text):
        if not new_text:
            self.entryVariable.set("Enter Letters Here.")
            return True

        if not (new_text.isalpha()):
            #print "Invalid Input Detected"
            self.entry.config(bg='red', fg='white')
            self.entry.focus_set()
            return False
        else:
            #print "Valid Input Detected"
            self.entry.config(bg='white', fg='black')
            return True

    def CheckWordLenEntry(self, new_text):
        if not new_text:
            self.wordLenVariable.set("0")
            return True

        if not (new_text.isdigit()):
            #print "WL Invalid Input Detected"
            self.wordLenEntry.config(bg='red', fg='white')
            self.wordLenEntry.focus_set()
            return False
        else:
            #print "WL Valid Input Detected"
            self.wordLenEntry.config(bg='white', fg='black')
            return True

    def OnButtonClick(self):
        self.resultsText['state'] = "normal"
        self.resultsText.delete(1.0, END)
        self.resultsText.insert(1.0, "Finding Words. Please Wait. . .")
        #self.resultsText['state'] = "disabled"
        self.master.update()
        # Check the Letters Entry and Word Len Entry
        if (self.entryVariable.get().isalpha()) and (
                self.wordLenEntry.get().isdigit()):
            self.entry.config(bg='white', fg='black')
            self.wordLenEntry.config(bg='white', fg='black')

            #self.resultsText['state'] = "normal"
            #self.resultsText.delete(1.0, END)
            #self.resultsText['state'] = "disabled"

            #Get the letters to use
            letterArr = str(self.entry.get())

            #Get the word length
            if self.wordLenEntry.get() == "":
                wordLen = 0
            else:
                wordLen = int(self.wordLenEntry.get())

    #### Build a list of possible words by running Permute on String[0-1] to String[0-length]
    #### read in the american-english list into an array.
    #### for each possible word, check it against american-english array if it exists add it to answer array if not already an answer
    #### only display answers that match the given wordLen
    #
    # compare fullWordList against dict and return matches
    # if wordLen given is 0 or blank, return ALL matching english words
    # if wordLen is not blank or 0, return only matches whose length = wordLen

    #convert all letters to lowercase
            letterArr = letterArr.lower()
            fullWordList = []
            a = time.clock()
            if wordLen == 0:
                #PermWordList = itertools.permutations(letterArr,len(letterArr))
                #for l in range(3,len(letterArr)+1):
                for l in range(2, len(letterArr) + 1):
                    PermWordList = list(itertools.permutations(letterArr, l))
                    for permWord in PermWordList:
                        combinedWord = ""
                        for w in range(0, len(permWord)):
                            combinedWord += permWord[w]
                        fullWordList.append(combinedWord)
                #	PermWordList = PermWordList + TempList

            else:
                PermWordList = itertools.permutations(letterArr, wordLen)
                PermWordList = list(PermWordList)
                for permWord in PermWordList:
                    combinedWord = ""
                    for w in range(0, len(permWord)):
                        combinedWord += permWord[w]
                    fullWordList.append(combinedWord)

            b = time.clock()
            exec_time_perm = (b - a)

            #fullWordList = sorted(set(fullWordList),key=len)
            fullWordList = sorted(set(fullWordList),
                                  key=lambda item: (-len(item), item),
                                  reverse=True)
            #fullWordList = fullWordList.sort(key=lambda item:(-len(item),item))

            #print "Full Word List: ", fullWordList

            numWordsFound = 0
            a = time.clock()
            # Enable the Results field and clear it
            self.resultsText['state'] = "normal"
            self.resultsText.delete(1.0, END)
            #self.start_loading(0)
            for checkWord in fullWordList:
                if (len(checkWord) > 1):
                    #if checkWord in dictList and (wordLen == 0 or wordLen == ""):
                    #		self.resultsText.insert(Tkinter.INSERT,checkWord)
                    #		self.resultsText.insert(Tkinter.INSERT,'\n')
                    #	elif checkWord in dictList and wordLen == len(checkWord):
                    if checkWord in dictList:
                        self.resultsText.insert(INSERT, checkWord)
                        self.resultsText.insert(INSERT, '\n')
                        numWordsFound += 1
            #self.stop_loading()
            b = time.clock()

            exec_time_search = (b - a)

            total_time = exec_time_perm + exec_time_search

            if numWordsFound == 0:
                self.resultsText.insert(1.0, "No Words Found.")
            else:
                headerStr = "     %d Words Found in %.2f seconds\n----------------------------------------\n\n" % (
                    numWordsFound, total_time)
                self.resultsText.insert(1.0, headerStr)

            #self.resultsText['state'] = "disabled"

        else:
            self.resultsText['state'] = "normal"
            self.resultsText.delete(1.0, END)
            if not (self.entryVariable.get().isalpha()):
                self.resultsText.insert(
                    1.0, "Letters field can only contain letters.")
                self.entry.config(bg='red', fg='white')
                self.entry.focus_set()
            elif not (self.wordLenEntry.get().isdigit()):
                self.resultsText.insert(
                    1.0, "Word length field can only contain digits.")
                self.wordLenEntry.config(bg='red', fg='white')
                self.wordLenEntry.focus_set()
            self.resultsText['state'] = "disabled"