Ejemplo n.º 1
0
def _on_mouse_entered_button(event: tkinter.Event) -> None:
    # Widgets have what are called "options" (the things you set with
    # keyword arguments when you construct them).  A widget's options are
    # accessible by using the indexing operator on the widget, using the
    # name of the option as the index.  In this case, we want to set the
    # 'text' option (which specifies the text displayed in the button).
    event.widget['text'] = _ENTERED_BUTTON_TEXT
Ejemplo n.º 2
0
def _on_mouse_entered_button(event: tkinter.Event) -> None:
    # Widgets have what are called "options" (the things you set with
    # keyword arguments when you construct them).  A widget's options are
    # accessible by using the indexing operator on the widget, using the
    # name of the option as the index.  In this case, we want to set the
    # 'text' option (which specifies the text displayed in the button).
    event.widget['text'] = _ENTERED_BUTTON_TEXT
Ejemplo n.º 3
0
 def paste_shape(self, *, deltax=15, deltay=15):
     """
     Paste selected shape from buffer.
     
     :param deltax: pasted shape offset in x direction in pixels.
     :type deltax: integer
     :param deltay: pasted shape offset in y direction in pixels.
     :type deltay: integer
     """
     self.TApp.paste_ctrl_v(Event())
Ejemplo n.º 4
0
    def get_current_img(self, event: tkinter.Event):
        # get the image source

        swipe = event.__getattribute__('keysym').lower()
        age = 'none'
        name = 'none'
        try:
            age = self.driver.find_element_by_xpath(
                '//*[@id="content"]/div/div[1]/div/main/div[1]/div/div/div[1]/div/div[1]/div[3]/div[6]/div/div[1]/div/span'
            ).text
        except:
            pass
        try:
            name = self.driver.find_element_by_xpath(
                '//*[@id="content"]/div/div[1]/div/main/div[1]/div/div/div[1]/div/div[1]/div[3]/div[6]/div/div[1]/div/div/span'
            ).text
        except:
            pass

        img_click_left = ActionChains(self.driver)
        img_click_right = ActionChains(self.driver)
        img_center_btn = self.driver.find_element_by_xpath(
            '//*[@id="content"]/div/div[1]/div/main/div[1]/div/div/div[1]/div/div[1]/div[1]'
        )
        img_click_left.move_to_element_with_offset(img_center_btn, 5, 5)
        img_click_left.click()
        img_click_right.move_to_element_with_offset(img_center_btn, 60, 5)
        img_click_right.click()

        xpath = '//*[@id="content"]/div/div[1]/div/main/div[1]/div/div/div[1]/div/div[1]/div[3]/div[1]/div[1]/div/div[' + \
            str(self.tkinter_current_pos) + ']/div/div[1]'
        try:
            img = self.driver.find_element_by_xpath(xpath)
            style = img.get_attribute('style')
            # print(img.get_attribute('style'))
            self.tkinter_current_pos += 1
        except Exception:
            print('failed to get img' + str(self.tkinter_current_pos))
            self.tkinter_current_pos = 1
            self.dislike()
            return

        img_url = style[style.find('("') + 2:style.find('")')]

        gurl_dict = {'age': age, 'name': name, 'img_url': img_url}

        if swipe == 'left':
            self.collect_nope_url(gurl_dict)
        else:
            self.collect_yea_url(gurl_dict)

        img_click_right.perform()
Ejemplo n.º 5
0
def CharacterGenerationBindFunc(ev: tk.Event, char: character.Character) -> None:
    sym: str = ev.__getattribute__("keysym")

    if sym.lower() == "r":
        char.SelfRegenerate()
        graphics.deleteAllText()
        graphics.after(1, char.PrintStats)
        graphics.after(1, addGenerationPromt)
    if sym == "Return":
        pass  # all is done
        graphics.after(1, nextFunc)
    if sym == "Escape":
        graphics.after(1, MainMenu)
Ejemplo n.º 6
0
    def _cb_mouse_wheel(self, event: tk.Event, ver: bool) -> None:
        """The mouse scroll callback that scrolls the window.

        Parameters
        ----------
        event : tk.Event
            The event information.
        ver : bool
            If True, scroll in vertical direction, else scroll in horizontal direction.
        """

        # Respond to Linux or Windows wheel event
        if getattr(event, "num") == 4:
            event.delta = 120

        elif getattr(event, "num") == 5:
            event.delta = -120

        if ver:
            self._canvas.yview_scroll(int(-1 * (event.delta / 120)), tk.UNITS)
        else:
            self._canvas.xview_scroll(int(-1 * (event.delta / 120)), tk.UNITS)
Ejemplo n.º 7
0
 def zoom(self, event: tk.Event, factor: float = None) -> None:
     if not factor:
         factor = ZOOM_IN if event.delta > 0 else ZOOM_OUT
     event.x, event.y = self.canvasx(event.x), self.canvasy(event.y)
     self.scale(tk.ALL, event.x, event.y, factor, factor)
     self.configure(scrollregion=self.bbox(tk.ALL))
     self.ratio *= float(factor)
     self.offset = (
         self.offset[0] * factor + event.x * (1 - factor),
         self.offset[1] * factor + event.y * (1 - factor),
     )
     logging.debug("ratio: %s", self.ratio)
     logging.debug("offset: %s", self.offset)
     self.app.statusbar.set_zoom(self.ratio)
     if self.wallpaper:
         self.redraw_wallpaper()
Ejemplo n.º 8
0
def MainMenuBindFunc(ev: tk.Event, id_x: MutableWrapper) -> None:
    sym: str = ev.__getattribute__("keysym")
    print(sym, ev)
    if sym == "Return":
        if id_x == 0:
            graphics.after(10, CharacterGeneration)
        elif id_x == 1:
            pass  # load game
        elif id_x == 2:
            pass  # instructions
        elif id_x == 3:
            print(id_x)
            graphics.destroyEvent(ev)
        return

    if sym == "Up":
        id_x[0] = (id_x[0] - 1) % 4
        graphics.after(1, mmenu.DrawMenu, id_x.value)
    if sym == "Down":
        id_x[0] = (id_x[0] + 1) % 4
        graphics.after(1, mmenu.DrawMenu, id_x.value)
Ejemplo n.º 9
0
    def _build_tk_event(self):
        """Builds TkEvent from QtEvent."""

        # Tkinter Event:
        # %# %b %f %h %k %s %t %w %x %y %A %E %K %N %W %T %X %Y %D

        # Source:
        # http://epydoc.sourceforge.net/stdlib/Tkinter.Event-class.html

        # TODO: Future improvement: Write setter method

        self.tk_event = Event()

        # serial - serial number of event - did no come to conclusion when used
        self.tk_event.serial = 42

        # num - mouse button pressed (ButtonPress, ButtonRelease)
        if type(self.qt_event) == QMouseEvent:
            self.tk_event.num = mouse_button_translator(self.qt_event.button(),
                                                        from_tk=False)
        else:
            self.tk_event.num = "??"

        # focus - whether the window has the focus (Enter, Leave)
        if type(self.qt_event) == QFocusEvent:
            self.tk_event.focus = self.qt_event.gotFocus()
        else:
            pass
            # Decided to pass this since it is not set usually.

        # height - height of the exposed window (Configure, Expose)
        # width - width of the exposed window (Configure, Expose)
        self.tk_event.height = "??"  # Set as "default"
        self.tk_event.width = "??"  # Set as "default"

        # keycode - keycode of the pressed key (KeyPress, KeyRelease)
        if type(self.qt_event) == QKeyEvent:
            # TODO: This need translation !!!
            self.tk_event.keycode = self.qt_event.key()
        else:
            self.tk_event.keycode = "??"

        # state - state of the event as a number (ButtonPress, ButtonRelease,
        #                         Enter, KeyPress, KeyRelease,
        #                         Leave, Motion)
        # state - state as a string (Visibility)
        if type(self.qt_event) in [QMouseEvent, QKeyEvent, QEnterEvent]:
            # TODO: This need translation !!!
            self.tk_event.state = self.qt_event.type()
            # TODO: + self.qt_event.modifiers()
            # TODO: No translation for Motion, Visibility
        else:
            self.tk_event.state = "??"

        # time - when the event occurred - only successors of QInputEvent
        if issubclass(type(self.qt_event), QInputEvent):
            self.tk_event.time = self.qt_event.timestamp()
        else:
            self.tk_event.time = "??"

        # x - x-position of the mouse
        # y - y-position of the mouse
        if type(self.qt_event) in [QMouseEvent, QEnterEvent]:
            self.tk_event.x = self.qt_event.x()
            self.tk_event.y = self.qt_event.y()
        else:
            self.tk_event.x = "??"
            self.tk_event.y = "??"

        # x_root - x-position of the mouse on the screen
        #          (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
        # y_root - y-position of the mouse on the screen
        #          (ButtonPress, ButtonRelease, KeyPress, KeyRelease, Motion)
        if type(self.qt_event) in [QMouseEvent]:
            self.tk_event.x_root = self.qt_event.screenPos().x()
            self.tk_event.y_root = self.qt_event.screenPos().y()
            # TODO: No translation for Motion
            # QKeyEvent does not have this.
        else:
            self.tk_event.x_root = "??"
            self.tk_event.y_root = "??"

        # char - pressed character (KeyPress, KeyRelease)
        if type(self.qt_event) == QKeyEvent:
            # TODO: This need translation !!!
            self.tk_event.char = self.qt_event.text()
        else:
            self.tk_event.char = "??"

        self.tk_event.send_event = False

        # keysym - keysym of the event as a string (KeyPress, KeyRelease)
        # keysym_num - keysym of the event as a number (KeyPress, KeyRelease)
        if type(self.qt_event) == QKeyEvent:
            # TODO: This need translation !!!
            self.tk_event.keysym = self.qt_event.text()
            self.tk_event.keysym_num = ord(self.qt_event.text())
        else:
            self.tk_event.keysym = "??"
            self.tk_event.keysym_num = "??"

        # type - type of the event as a number
        # TODO: This need translation !!!
        self.tk_event.type = self.qt_event.type()

        # widget - widget in which the event occurred
        # There is no way to get this in PyQt.

        # delta - delta of wheel movement (MouseWheel)
        if type(self.qt_event) == QWheelEvent:
            self.tk_event.delta = self.qt_event.angleDelta()
        else:
            self.tk_event.delta = 0

        return self.tk_event
Ejemplo n.º 10
0
def mouse_entered_button(event: tkinter.Event) -> None:
    event.widget['text'] = 'I am'
Ejemplo n.º 11
0
def mouse_exited_button(event: tkinter.Event) -> None:
    event.widget['text'] = 'anime'
Ejemplo n.º 12
0
    def _on_mouse_down(self, event: tkinter.Event):
        self._canvas.delete(tkinter.ALL)
        draw_tile = False
        canvas_width = self._canvas.winfo_width()
        canvas_height = self._canvas.winfo_height() - 130
        w_ratio = canvas_width/int(self.list_entries[1])
        h_ratio = canvas_height/int(self.list_entries[0])
        if event.x > int(self.list_entries[1]) * 100:
            x_dif = canvas_width - int(self.list_entries[1]) * 100
            event.x = event.x - x_dif
        if event.y > int(self.list_entries[0]) * 100:
            y_dif = canvas_height - int(self.list_entries[0]) * 100
            event.y = event.y - y_dif
        x = str(event.x)
        y = str(event.y)
        if event.x < 0:
            event.x = 0
        elif int(x[1:]) > 50:
                event.x = event.x - 50
        if event.y < 0:
            event.y = 0
        elif int(y[1:]) > 50:
            event.y = event.y - 50
        user_x = round(event.x, -(int(len(x)) - 1)) 
        user_y = round(event.y, -(int(len(y)) - 1)) 
        tile_x = user_x//100
        tile_y = user_y//100
        potential = (tile_y, tile_x)
        if tile_x < 0 or tile_x > int(self.list_entries[1]) or tile_y < 0 or tile_y > int(self.list_entries[0]):
            draw_tile = False
        elif othello.valid_move(potential) == False:
            draw_tile = False
        else:
            draw_tile = True
        if draw_tile == True:
            if othello.turn == 'B':
                self._canvas.create_oval(
                    user_x, user_y, user_x + 100, user_y + 100, fill = 'Black')
            elif othello.turn == 'W':
                self._canvas.create_oval(
                    user_x, user_y, user_x + 100, user_y + 100, fill = 'White')
            othello.change_turn()
            draw_tile = False
            
##This is where the game will check the status
##to see if there's a winner or not. If there is,
##then it will make a new window that pops up
##declaring the game winner/status. When Okay button
##is hit, it will close everything.

        if self._check_status() == True or othello.change_turn == False:
            self.win_window = tkinter.Toplevel()
            win_label = tkinter.Label(
                master = self.win_window,
                textvariable = self.win_text,
                font = DEFAULT_FONT)
            win_label.grid(row = 0, column = 0,
                           columnspan = 3,
                           padx = 10, pady = 10,
                           sticky = tkinter.N)
            exit_button = tkinter.Button(
                master = self.win_window, text = 'Okay', font = DEFAULT_FONT,
                command = self._close_windows)
            exit_button.grid(
                row = 1, column = 0,
                padx = 10, pady = 10,
                sticky = tkinter.S)
        self._draw_board()
        B_count = 0
        W_count = 0
        for i in range(othello.input_rows):
            for j in range(othello.input_columns):
                if othello.board[i][j] == 'B':
                    B_count = B_count + 1
                elif othello.board[i][j] == 'W':
                    W_count = W_count + 1
        self.B_score = B_count
        self.W_score = W_count
        self._score_board = tkinter.Label(
            master = self._game_window,
            text = 'Score:\nBlack:{}\nWhite:{}\n Turn:{}'.format(self.B_score, self.W_score, othello.turn),
            font = DEFAULT_FONT,
            background = 'Grey')
        self._score_board.grid(
            row = 0, column = 0,
            sticky = tkinter.S + tkinter.W + tkinter.E)
Ejemplo n.º 13
0
    def __init__(self, outpath, textwidget):
        self.doc = Document(outpath)
        self.outpath = outpath
        self.text = []
        # A list the length of the document's plaintext, where each is a triple
        # of positions (par,run, char)
        # specifying the/ character's position in the docx object.
        self.txtodocpos = []
        # The tkinter text widget with which the doc is to be binded for live editing.
        self.textwidget = textwidget
        # A boolean tracking whether the command button is being held
        self.cmnd_press = False
        self.ctrl_press = False
        # tkinter textwidget indices of form being replaced
        self.formstart = '1.0'
        self.formstart = '1.0'
        self.insert = self.formstart

        row, i, j, k = 0, 0, 0, 0
        for p in self.doc.paragraphs:
            self.text += ['']
            self.txtodocpos += [[]]
            for r in p.runs:
                self.text[row] += r.text
                for c in r.text:
                    self.txtodocpos[row] += [(i, j, k)]
                    k += 1
                    # if c == '\n':
                    #     column =0
                    #     row += 1
                    #     self.txtodocpos[row] = []
                k = 0
                j += 1
            j = 0
            i += 1
            # if p.runs:
            print('par ' + str(i - 1) + ' has text')
            row += 1

        # print(self.txtodocpos)

        def key(event):
            ''' Add one character to document.'''
            print(event.keysym, event.type, event.char)
            # if self.cmd_bool or self.ctrl_bool:
            #     print('command/control key is depressed - not recording keystrokes as text')
            #     return
            if event.keysym == 'form2doc_replacement':
                self.textwidget.mark_set('insert', self.insert)
            if event.char and event.char not in [
                    u'\uf700', u'\uf701', u'\uf702', u'\uf703'
            ]:
                # delete selected characters, if any
                selection_len = len(event.widget.get('sel.first', 'sel.last'))
                if selection_len == 0:
                    print('entering character w/o deletion')
                    txpos = self.textwidget.index('insert').split('.')
                else:
                    print('entering character after deletion')
                    txpos = self.textwidget.index('sel.first').split('.')
                    backspace(event)
                print('selection length: ' + str(selection_len))
                row, col = int(txpos[0]) - 1, int(txpos[1])
                print(row, col)
                txtodocpos_row = self.txtodocpos[row]
                # print(txtodocpos_row)
                # in case we are adding to the end of a paragraph
                if col == len(txtodocpos_row):
                    # in case the paragraph is empty
                    if col == 0:
                        p, r, c = row, 0, 0
                    else:
                        docpos = txtodocpos_row[col - 1]
                        p, r, c = docpos[0], docpos[1], docpos[2] + 1
                else:
                    docpos = txtodocpos_row[col]
                    p, r, c = docpos[0], docpos[1], docpos[2]
                currun = self.doc.paragraphs[p].runs[r]
                currun.text = currun.text[:c] + event.char + currun.text[c:]
                # insert new pos-list item
                self.txtodocpos[row].insert(col, (p, r, c))
                # print(self.txtodocpos[row])
                # adjust the char-pos of all positions left in the run
                # c += 1
                ccol = col
                print(len(currun.text), currun.text)
                while c < len(currun.text):
                    self.txtodocpos[row][ccol] = (p, r, c)
                    # print(self.txtodocpos[row])

                    ccol += 1
                    c += 1
                self.text[row] = self.text[row][:col] + event.char + self.text[
                    row][col + 1:]

                docpos0 = self.txtodocpos[row]
                # print(docpos0)

        # from Scanny: https://github.com/python-openxml/python-docx/issues/33
        def delete_paragraph(paragraph):
            p = paragraph._element
            p.getparent().remove(p)
            p._p = p._element = None

        def backspace(event):
            ''' For cutting, backspacing, deleting. Deletes moving backward from cursor. '''
            #     try:
            if event.keysym == 'form2doc_replacement':
                self.textwidget.mark_set('sel.first', self.formstart)
                self.textwidget.mark_set('sel.last', self.formend)
                self.insert = self.formstart

            print('sel.first in backspace: ',
                  self.textwidget.index('sel.first'))
            print('sel.last in backspace: ', self.textwidget.index('sel.last'))

            # print(self.textwidget.get('sel.last', 'end'))
            txpos = self.textwidget.index('sel.last').split('.')
            # delete multi-character selection in text-widget
            selection_len = len(event.widget.get('sel.first', 'sel.last'))
            print('selection: ' +
                  str(event.widget.get('sel.first', 'sel.last')))
            if selection_len == 0:
                selection_len = 1

    #     except TclError:
    #         txpos = self.textwidget.index('insert').split('.')
    #         # or else delete a single character
    #         selection = 1
            print(str(selection_len) + ' characters set for deletion')
            print('textwidget index: ', txpos)
            row, col = int(txpos[0]) - 1, int(txpos[1])
            print('text in liveDoc paragraph: ', self.text[row])
            # print('text in ocx paragraph: ', self.doc,[row])
            # assuming a new line equates to a new paragraph
            print(len(self.doc.paragraphs),
                  'paragraphs in docx object, selecting paragraph number ',
                  row)
            curpar = self.doc.paragraphs[row]
            s = 0
            while s < selection_len:
                # delete moving backwards from cursor
                while col - 1 not in range(len(self.text[row])):
                    # delete empty paragraph
                    if not self.text[row]:
                        self.text.pop(row)
                        self.txtodocpos.pop(row)
                        delete_paragraph(self.doc.paragraphs[row])
                    row -= 1
                    col = len(self.text[row])
                    s += 1

                docpos = self.txtodocpos[row][col - 1]
                p, r, c = docpos[0], docpos[1], docpos[2] - 1
                currun = self.doc.paragraphs[p].runs[r]
                print('text widget position, row: ', row, 'column: ', col)
                # print(self.text[row])
                print(docpos)
                print(currun.text)
                self.text[row] = self.text[row][:col -
                                                1] + self.text[row][col:]
                currun.text = currun.text[:c + 1] + currun.text[c + 2:]
                self.txtodocpos[row] = self.txtodocpos[row][:-1]
                col -= 1
                s += 1
                self.textwidget.mark_set('sel.first', '1.0')
                self.textwidget.mark_set('sel.last', '1.0')
            # print(self.text[row])
            # print(currun.text)

        def paste(event):
            ''' Pastes text on the clipboard into the cursor position.
            '''
            cliptext = event.widget.clipboard_get()
            print('cliptext: ' + cliptext)
            # delete active selection, or form2doc field
            if (not cliptext and self.textwidget.get('sel.first', 'sel.last')
                ) or event.keysym == 'form2doc_replacement':
                backspace(event)
                # write reverse so as to skip moving the cursor
            for c in cliptext[::-1]:
                event.char = c
                key(event)
                if event.keysym == 'form2doc_replacement':
                    self.insert = self.insert.split('.')[0] + '.' + str(
                        int(self.insert.split('.')[1]) + 1)

        def cmdBool(event):
            self.cmnd_press = not self.cmnd_press
            print('cmnd_press: ' + str(self.cmnd_press))

        def ctrlBool(event):
            self.cmnd_press = not self.cmnd_press
            print('ctrl_press: ' + str(self.cmnd_press))

        def specialBool(event):
            # when these keys are depressed, further keystrokes should not be registered as entered text
            if event.keysym == 'Meta_L': cmdBool(event)
            elif event.keysym == 'Control_L': ctrlBool(event)

        textwidget.bind('<KeyPress>', key)
        # textwidget.bind('<KeyRelease>', specialBool)
        textwidget.bind('<BackSpace>', backspace)
        textwidget.bind('<Command-v>', paste)
        # textwidget.bind('<Command-c', None)
        # textwidget.bind('<Command-x>',None)
        textwidget.bind('<Command-KeyPress>',
                        lambda x: print('command keypress'))
        textwidget.bind('<Control-KeyPress>',
                        lambda x: print('control keypress'))

        self.textwidget.insert("insert", '\n'.join(self.text))
        # Empty event obkject allowing for simulation of keystrokes
        event = Event()
        event.keysym = 'form2doc_replacement'
        event.type = 'sme'
        compiled_rules = compileRules()
        p = 1
        for par in self.text:
            print('searching par ', p)

            for rule in compiled_rules:
                for replacee in rule.replacees:
                    replacement = rule.replacement.strip('\n')
                    # find replacement positions for par in self.text:
                    # print('docLive text: ', self.text)
                    # print('docLive text length (i.e., num paragraphs): ', len(self.text))
                    c = par.upper().find(replacee.upper())
                    while replacee in par:
                        print('replacee: ' + replacee)
                        print('replacement: ' + rule.replacement)

                        print('found replacee at ', c)
                        # the position of the current replacee in the paragraph
                        # print(par)
                        print('replacee index: ' + str(c))
                        print('paragraph length: ' + str(len(par)))
                        print('replacee from paragraph: ',
                              par[c:c + len(replacee)])
                        if c > 2 and par[c - 2] == '.':
                            print('capitalizing replacement')
                            replacement = replacement.capitalize()
                        elif c > 4 and par[c - 4:c - 1] == '(n)':
                            r = replacement[0]
                            self.textwidget.mark_set("insert",
                                                     "%d.%d" % (p, c - 1))
                            if r == 'a' or r == 'e' or r == 'u' or r == 'i' or r == 'o':
                                print('replacement follows \'an\'')
                                backspace(event)
                                self.textwidget.mark_set(
                                    "insert", "%d.%d" % (p, c - 3))
                                backspace(event)
                                c -= 2
                            else:
                                print('replacement follows \'a\'')
                                backspace(event)
                                backspace(event)
                                backspace(event)
                                c -= 3
                        self.textwidget.clipboard_clear()
                        self.textwidget.clipboard_append(replacement)
                        # self.textwidget.mark_set("field.start", "%d.%d" % (p, c))
                        # print('field.start',"%d.%d" % (p, c) )
                        # print('replacee length: '+ str(len(replacee)))
                        # # print('sel.first position: '+self.textwidget.get('sel.first'))
                        self.formstart = "%d.%d" % (p, c)
                        c += len(replacee)
                        self.formend = "%d.%d" % (p, c)
                        # self.textwidget.mark_set("field.end", "%d.%d" % (p, c))
                        # print('field.end',"%d.%d" % (p, c) )
                        # print('sel.first position: '+self.textwidget.get('sel.first'))
                        print(
                            'selection: ' +
                            self.textwidget.get(self.formstart, self.formend))
                        # print('affected paragraph: ', par)
                        event.widget = self.textwidget
                        self.textwidget.delete(self.formstart, self.formend)
                        self.textwidget.insert(self.formstart, replacement)
                        par = par[:c - len(replacee)] + replacement + par[c:]
                        print('pasting with paragraph ', p, 'and column ', c)
                        paste(event)
                        c = c - len(replacee) + par[c - len(replacee):].upper(
                        ).find(replacee.upper())
                        print('found ', replacee, 'at ', c)
                        print('paragraph: ', par)
                        print('new widget text: ',
                              textwidget.get('1.0', 'end'))
            p += 1
Ejemplo n.º 14
0
def on_mouse_entered_button(event: tkinter.Event):
    event.widget["text"] = "In button"
Ejemplo n.º 15
0
 def __init__(self, port):
     Thread.__init__(self)
     self.reset_flag = Event()
     self.port = port
     self.reading = ""
Ejemplo n.º 16
0
class SerialThread(Thread):
    def __init__(self, port):
        Thread.__init__(self)
        self.reset_flag = Event()
        self.port = port
        self.reading = ""

    def run(self):
        while not self.reset_flag.is_set():
            self.read_from_port()

    def reset(self):
        self.reset_flag.set()

    # lock and global for serial reading
    # Serial read thread

    def read_from_port(self):
        while True:
            try:
                self.reading = self.port.readline().decode("utf-8")
                print("Reading: " + self.reading)
                self.handle_data()
            except IOError:
                while True:
                    try:
                        self.port.close()
                        self.port.open()
                    except IOError:
                        pass
                    else:
                        break

    def handle_data(self):
        out = self.reading
        if "Firmware ver. 1.6" in out:
            gui_lock.acquire()
            w.title.insert(END, "Welcome to the Capstone Fair!")
            w.experience.insert(
                END,
                "Maybe it'd be interesting to put one of the objects on the receiver?"
            )
            gui_lock.release()
            out = ""

        if "place a tag." in out:
            out = ""

        if ":L:" in out:
            print("found lights")
            out = ""

        # the text that describes the experience is updated when the videos and images are
        if ":V:" in out:
            file_name = (
                (out.replace(":V:", "text_")).split(".")[0]).rstrip() + ".txt"
            with open(file_name, 'r') as f:
                gui_lock.acquire()
                w.experience.delete("1.0", END)
                w.experience.insert(INSERT, f.read())
                w.toggle_video(out.replace(":V:", "").rstrip())
                gui_lock.release()

        if ":P:" in out:
            file_name = (
                (out.replace(":P:", "text_")).split(".")[0]).rstrip() + ".txt"
            with open(file_name, 'r') as f:
                gui_lock.acquire()
                w.experience.delete("1.0", END)
                w.experience.insert(INSERT, f.read())
                w.toggle_picture(out.replace(":P:", "").rstrip())
                gui_lock.release()

        if ":Pl:" in out:
            winsound.PlaySound((out.replace(":Pl:", "")).rstrip(),
                               winsound.SND_ASYNC)

        if ":W:" in out:
            print("parsing website:")
            out = ""

        if ":We:" in out:
            gui_lock.acquire()
            w.experience.insert(END,
                                "going to website:" + out.replace(":We:", ""))
            gui_lock.release()
            webbrowser.open(out.replace(":We:", ""), autoraise=False)
            out = ""

        if ":S:" in out:
            gui_lock.acquire()
            w.experience.insert(
                END, "Searching for Spotify artist:" + out.replace(":S:", ""))
            gui_lock.release()
            # print("searching for Spotify artist:")
            # print(out.replace(":S:", ""))
            result = sp.search(out.replace(":S:", ""))
            for key in result['tracks']['items']:
                pprint.pprint(key['name'], depth=1)
                pprint.pprint(key['external_urls']['spotify'])

            trim = result['tracks']['items'][0]['external_urls']['spotify']

            x = lambda: webbrowser.open_new(trim.replace("'", ""))
            t = Thread(target=x)
            t.start()
            out = ""

        # if ":R:" in out:
        #     duration = [int(s) for s in out.split(":") if s.isdigit()]
        #     print(duration)
        #     print("Recording for " + str(duration[0]) + " seconds...")
        #     print("Finished")
        #     # if ":P:" in out:
        #     #     sd.wait()
        #
        #     # with sf.SoundFile("CDEFO.wav", mode='x', samplerate=44100, channels=2, subtype="PCM_24") as file:
        #     #     file.write(recording)
        #     lock.acquire()
        #     out = ""
        #     lock.release()

        if ":End:" in out:
            out = ""

        if "Cleanup finished :Stop:" in out:
            gui_lock.acquire()
            w.experience.delete(1.0, END)
            gui_lock.release()
Ejemplo n.º 17
0
def on_mouse_exited_button(event: tkinter.Event):
    event.widget["text"] = "Out of button"