def find_urls(text: tkinter.Text) -> Iterable[Tuple[str, str]]: searching_begins_here = '1.0' while True: match_start = text.search(r'\mhttps?://[a-z]', searching_begins_here, 'end', nocase=True, regexp=True) if not match_start: # empty string means not found break # urls end on space, quote or end of line end_of_line = f'{match_start} lineend' match_end = text.search( r'''["' ]''', match_start, end_of_line, regexp=True) or end_of_line # support parenthesized urls and commas/dots after urls if text.get(f'{match_end} - 1 char') in {',', '.'}: match_end += ' - 1 char' url = text.get(match_start, match_end) closing2opening = { ')': '(', '}': '{', '>': '<' } # {url} is useful for tcl code if url[-1] in closing2opening and closing2opening[url[-1]] not in url: # url isn't like "Bla(bla)" but ends with ")" or similar, assume that's not part of url match_end = f'{match_end} - 1 char' yield (match_start, match_end) searching_begins_here = match_end
def _all_words_in_file_completions( textwidget: tkinter.Text) -> List[Completion]: match = re.search(r'\w*$', textwidget.get('insert linestart', 'insert')) assert match is not None before_cursor = match.group(0) replace_start = textwidget.index(f'insert - {len(before_cursor)} chars') replace_end = textwidget.index('insert') counts = dict( collections.Counter([ word for word in re.findall(r'\w+', textwidget.get('1.0', 'end')) if before_cursor.casefold() in word.casefold() ])) if counts.get(before_cursor, 0) == 1: del counts[before_cursor] return [ Completion( display_text=word, replace_start=replace_start, replace_end=replace_end, replace_text=word, filter_text=word, documentation=word, ) for word in sorted(counts.keys(), key=counts.__getitem__) ]
def insert_char(text: tk.Text, char: str, raw: str = '', go=True): try: sel = text.get(tk.SEL_FIRST, tk.SEL_LAST) except tk.TclError: pass else: insert_text = raw + sel + char text.delete(tk.SEL_FIRST, tk.SEL_LAST) text.edit_separator() text.insert(tk.INSERT, insert_text) return 'break' index = str(text.index(tk.INSERT)).split('.') if text.get(f'{index[0]}.{int(index[1])}') == char: if char == raw: text.mark_set(tk.INSERT, f'{index[0]}.{int(index[1]) + 1}') text.see(tk.INSERT) return 'break' if raw: text.insert(tk.INSERT, raw) if (char != raw) or (char == '"') or char == "'": text.insert(tk.INSERT, char) if go: text.mark_set(tk.INSERT, f'{index[0]}.{int(index[1]) + 1}') text.see(tk.INSERT) return 'break'
def typeset_Text(content: str, Text: tk.Text, mode: str = "w") -> str: mode = mode.lower() if mode not in "aw": raise ValueError(f"{mode} should be either w(rite) (default) or a(ppend).") size = len(Text.get("1.0", tk.END)) if mode == "w" or size > 1500: clear_text(Text) # Text.insert(tk.END, "--cleared--") print(f"> {Text} cleared") if not content.endswith(EOL): content += EOL Text.insert(tk.END, content) return Text.get("1.0", tk.END)
def find_merge_conflicts(textwidget: tkinter.Text) -> List[List[int]]: result = [] current_state = "outside" for lineno in range(1, int(textwidget.index("end - 1 char").split(".")[0]) + 1): line = textwidget.get(f"{lineno}.0", f"{lineno}.0 lineend") # Line might contain whitespace characters after '<<<<<<< ' if line.startswith("<<<<<<< "): expected_current_state = "outside" new_state = "first" elif line == "=======": expected_current_state = "first" new_state = "second" elif line.startswith(">>>>>>> "): expected_current_state = "second" new_state = "outside" else: int("123") # needed for coverage to notice that the continue runs continue if current_state != expected_current_state: # Something is funny. Maybe the file contains some things that make # it look like git merge conflict, but it really isn't that. return [] current_state = new_state if new_state == "first": result.append([lineno]) else: result[-1].append(lineno) if current_state == "outside": return result return []
def export_to_eqdkp(d:tk.Text, link:str, usr:str, pw:str): browser = webdriver.Chrome(CHROME_DRIVER_PATH) browser.get(link) if 'Zugriff verweigert' in browser.page_source: __login(browser, usr, pw) btn_add_item:WebElement = browser.find_element_by_xpath("//button[@id='add-item-btn']") zähler = 0 pattern = r'[a-zA-Z\' \[\]\w\-]+[\t]{1}[0-9]+[\t]{1}[a-zA-Z_\w]+[\t]{1}[0-9]+' zeilen:str = d.get('0.0', 'end-1c') match = re.findall(pattern, zeilen) for d in match: dd = d.split('\t') ds = Datensatz(dd[0][1:-1], int(dd[1]), dd[2], int(dd[3])) zähler += 1 # Ist das gleiche wie btn_add_item.click() wird jetzt aber über JavaScript # ausgeführt und somit muss das element nicht im Sichtfeld / Anzeigebereich # liegen um ausgeführt zu werden browser.execute_script("arguments[0].click();", btn_add_item) #btn_add_item.click() sleep(0.25) seiten_elemente:WebElement = browser.find_elements_by_xpath( "//input[@id='items_"+str(zähler)+"']/../..//input") if(len(seiten_elemente) > 0): browser.find_element_by_xpath("//input[@id='items_"+str(zähler)+"']/../..//button").click() seiten_elemente[1].send_keys(ds.item) seiten_elemente[2].send_keys(ds.id) seiten_elemente[3].send_keys(ds.wert) tmp = browser.find_elements_by_xpath("//div[@class='ui-multiselect-filter']/../../div/div/input") tmp[zähler+2].send_keys(ds.spieler) sleep(0.25) browser.find_elements_by_xpath("//div[@class='ui-multiselect-filter']/../..//li/a[@class='ui-multiselect-all']")[zähler+2].click() browser.find_element_by_xpath("//input[@id='items_"+str(zähler)+"']/../..//button").click() else: pass
def raid_anlegen(link:str, usr:str, pas:str, d:tk.Text, from_logs:bool) -> None: spieler = [] thread_read_data = None if from_logs: raise NotImplementedError() else: thread_read_data = LeseBonusDKP(d.get('0.0', 'end-1c')) thread_read_data.start() browser = webdriver.Chrome(CHROME_DRIVER_PATH) browser.get(link) if 'Zugriff verweigert' in browser.page_source: __login(browser, usr, pas) # xpath zum Button # //button[@class='mainoption'][2] browser.find_element_by_xpath("//button[@class='mainoption'][2]").click() # Wähle das DKP Punkte Konto BWL aus browser.find_element_by_xpath("//select[@id='event']//option[@value='11']").click() # Öffne die Eingabe für die Raid-teilnemher browser.find_element_by_xpath("//button[@id='raid_attendees_ms']").click() # Eingabefeld Filter für Raid-Teilnehmer suchfeld:WebElement = browser.find_element_by_xpath("//div[@class='ui-multiselect-menu ui-widget ui-widget-content ui-corner-all'][1]//div[@class='ui-multiselect-filter']/input") # Allte Teilnehmer auswählen. btn_yes_suche: WebElement = browser.find_element_by_xpath("//div[@class='ui-multiselect-menu ui-widget ui-widget-content ui-corner-all'][1]//a[@class='ui-multiselect-all']/span[2]") if from_logs: raise NotImplementedError() else: spieler.extend(thread_read_data.join()) for s in spieler: suchfeld.send_keys(s) sleep(0.7) btn_yes_suche.click() suchfeld.clear()
def valid_check(ical_url: tk.Text, lang_var: tk.StringVar): """Ensure that given ical URl is valid and that a language was selected.""" valid = True if (ical_url.get("1.0", tk.END)[:46].strip() != "https://kronox.hkr.se/setup/jsp/SchemaICAL.ics" and ical_url.get("1.0", tk.END)[:46].strip() != "https://schema.hkr.se/setup/jsp/SchemaICAL.ics"): messagebox.showinfo("Error", "Invalid Kronox schema URL") valid = False elif lang_var.get() == "1": messagebox.showinfo("Error", "You must select a language") valid = False return valid
def handle_send(input_box: tk.Text): """ Executed when the user presses send. It will get and clear the text box then send the message. The message will be put straight into the list of messages on the client side. This is done so that the message doesn't need to be sent to the server and back again. If the server cannot be contacted, a message is displayed to the user to restart. Parameter: input_box (tk.Text): Text box containing the message """ msg = input_box.get("1.0", tk.END).rstrip() input_box.delete("1.0", tk.END) try: mp.send_msg_protocol(s, msg, NAME) # Create a label with the clients message and add it to the frame label = tk.Label(text='You:\n' + msg, master=frame, justify='left', wraplength=LABEL_WIDTH, relief='raised') label.pack(anchor='w') if msg == DISCONNECT: window.destroy() s.close() except ConnectionAbortedError: msgRcvQueue.put('Lost connection with server, please restart') except OSError: msgRcvQueue.put('Lost connection with server, please restart')
def _create_change(self, widget: tkinter.Text, start: str, end: str, new_text: str) -> Change: start_line = int(start.split(".")[0]) end_line = int(end.split(".")[0]) return Change( start=[start_line, count(widget, f"{start_line}.0", start)], end=[end_line, count(widget, f"{end_line}.0", end)], old_text_len=len(widget.get(start, end)), new_text=new_text, )
def btn_get_text_data_event(self, text: tk.Text): if self.chat_with == '': messagebox.showerror(message='请先指定联系人,再发送消息', parent=self.root) return None text_content = text.get('1.0', tk.END).strip('\n').strip(' ') text.delete('1.0', tk.END) if len(text_content) == 0: return None temp = MessageNode('text', time.time(), text_content, self.username, self.chat_with) self.output_one_message(temp, sending=True) self.client.send_queue.put(temp)
def show_entries(_, title: str, temperature: tk.DoubleVar, values_entry: tk.Text): title_str = title.format(temperature.get()) try: mbox.showinfo( "Extra Point Viewer", "{}\n{}".format( title_str, "\n".join("{}. {}".format(i + 1, x.strip()) for i, x in enumerate( values_entry.get(1.0, tk.END).split(","))))) except ValueError: mbox.showwarning( title_str, "Text in the field is malformed, please update the values.")
def find_urls(text: tkinter.Text, start: str, end: str) -> Iterable[Tuple[str, str]]: match_ends_and_search_begins = start while True: match_start = text.search(r"\mhttps?://[a-z]", match_ends_and_search_begins, end, nocase=True, regexp=True) if not match_start: # empty string means not found break url = text.get(match_start, f"{match_start} lineend") before_url = (None if text.index(match_start) == "1.0" else text.get(f"{match_start} - 1 char")) # urls end on space or quote url = url.split(" ")[0] url = url.split("'")[0] url = url.split('"')[0] open2close = {"(": ")", "{": "}", "<": ">"} close2open = {")": "(", "}": "{", ">": "<"} if before_url in open2close and open2close[before_url] in url: # url is parenthesized url = url.split(open2close[before_url])[0] if url[-1] in close2open and close2open[url[-1]] not in url: # url isn't like "Bla(bla)" but ends with ")" or similar, assume that's not part of url url = url[:-1] # urls in middle of text: URL, and URL. url = url.rstrip(".,") match_ends_and_search_begins = f"{match_start} + {len(url)} chars" yield (match_start, match_ends_and_search_begins)
def export_to_eqdkp_world_buffs( link:str, usr:str, pas:str, d:tk.Text, shared_data:BonusDKP, lock ) -> None: thread_read_data = LeseBonusDKP(d.get('0.0', 'end-1c'), True) thread_read_data.start() punkte = thread_read_data.join() thread_schreibe_daten = SchreibeBonusDKP(usr, pas, link, shared_data, punkte, lock) thread_schreibe_daten.start() thread_schreibe_daten.join() # https://www.canadian-crew.de/index.php/Points.html?s=&sort=7%7cdesc&mdkpid=0&filter=&show_twinks=1 # Finde alle Namen von EQDKP # //table//tr/td[2]/a/span # Finde Punkte zu den Namen # //table//tr/td[9]
def readFasta(Text): try: seq = [] seqNum = -1 tempText = Text.get("0.0", "end").splitlines() for line in tempText: if (line[0] == '>'): seqNum += 1 seq.append("") continue else: seq[seqNum] += line #temp #print(seq) return seq except BaseException: print("WrongInput")
def check_extra_point(self, text: tk.Text, point_num: int, input_type: str) -> bool: not_enough_error = str( "Extra point {} doesn't have the same amount of {} as there are fbgs. To get a better " "view of the elements in the text box click on the unit label to the right of the text " "box.").format(point_num, input_type) invalid_error = str( "Extra point {} has invalid {}, ensure that all the values in the text box are " "decimal numbers. To get a better view of the elements in the text box click on the unit " "label to the right of the text box.").format( point_num, input_type) error_title = "Configuration Error" number_of_fbgs = sum(len(x) for x in self.sn_ents) try: values = [float(x) for x in text.get(1.0, tk.END).split(",")] if len(values) != number_of_fbgs: mbox.showerror(error_title, not_enough_error) return False except ValueError: mbox.showerror(error_title, invalid_error) return False return True
def code_color(text: tk.Text, style=None): """color_config(text) p = Percolator(text) d = ColorDelegator() p.insertfilter(d)""" code_color_object = get_style_by_name(style or highlight_name) text.config(bg=code_color_object.background_color, bd=0) try: if not code_color_object.highlight_color: raise AttributeError text.config(selectbackground=code_color_object.highlight_color) except AttributeError: text.config(selectbackground='blue') code_color_config = code_color_object.styles black_colors = ('#000000', '#202020', '#232629', '#111111', '#2f1e2e', '#1e1e27', '#272822', '#002b36') if text.cget('bg') in black_colors: text.config(insertbackground='white', fg='white') else: text.config(insertbackground='black', fg='black') for i in range(count): text.tag_remove(i, 0.0, tk.END) def colorize(*args): global count row1, col1 = args[0].start row1, col1 = str(row1), str(col1) row2, col2 = args[0].end row2, col2 = str(row2), str(col2) start = ".".join((row1, col1)) end = ".".join((row2, col2)) text.tag_add(str(count), start, end) try: try: text.tag_config(str(count), foreground=args[1].replace(':', ' ').split(' ')[-1], font=args[2]) except IndexError: text.tag_config(str(count), foreground=args[1].replace(':', ' ').split(' ')[-1]) except tk.TclError: try: text.tag_config(str(count), foreground=args[1].replace(':', ' ').split(' ')[0]) except tk.TclError: text.tag_config(str(count), font=(args[1].replace(':', ' ').split(' ')[-1], font_size + 1)) count += 1 try: for i in tokenize.tokenize( io.BytesIO(text.get(1.0, tk.END).encode("utf-8")).readline): if i.type == 1: if i.string in keyword.kwlist: colorize(i, code_color_config[Keyword]) elif i.string in dir(builtins): colorize(i, code_color_config[Name.Builtin]) elif i.string in ['self', 'cls']: colorize( i, code_color_config[Keyword.Type] or code_color_config[Keyword]) else: if text.cget('bg') not in black_colors: colorize(i, 'black') else: colorize(i, 'white') if i.type == tokenize.STRING: colorize(i, code_color_config[String]) elif i.type == tokenize.NUMBER: colorize(i, code_color_config[Number]) elif i.type == tokenize.COMMENT: if text.cget('bg') in black_colors: colorize( i, code_color_config[Comment.Special] or code_color_config[Comment]) else: colorize(i, code_color_config[Comment]) elif i.type == 53: if i.string == "," or i.string == "." or i.string == ":": colorize(i, code_color_config[Keyword]) elif i.string == "(" or i.string == ")" or i.string == "[" \ or i.string == "]" or i.string == "{" or i.string == "}": colorize(i, "darkred") else: colorize(i, "green") except (tokenize.TokenError, SyntaxError): pass
def log(message, tex: tk.Text): # dont let console exceed 1 kB if (len(tex.get(1.0, tk.END).encode('utf-8')) > 1024): tex.delete(1.0, tk.END) tex.insert(tk.END, message) # insert message tex.see(tk.END) # scroll if necessary
def extract_info(thing: tk.Text, is_list=False): if is_list: return thing.get(1.0, 50.0)[0:-1].split('\n') else: return thing.get(1.0, 50.0)[0:-1]
def get( self, index1 = None, index2 = None ): if index1 is None : commande = Text.get(self, self.start_commande, 'end') return(commande) else : return(Text.get(self, index1, index2))
def retrieve_content(self, text_widget: tk.Text): content = text_widget.get("1.0", tk.END) return str(content)
def TKinterSetup(): Root = EnvSetup() ################################################################################################################menu MenuFrame = Frame(Root) #menu window area MenuFrame.place(relx=0, rely=0, relwidth=1, relheight=1) #placing the menu frame in the window MenuTopLabel = Label(MenuFrame, text='Welcome to\nPositivity.Jar', font=('Courier', 32), bd=10) #welcome label MenuTopLabel.place(anchor='n', relx=HRel, rely=0.015, relwidth=1, relheight=0.2) #placing the label def ButtonSelection(Selection=int()): nonlocal Sel Sel = Selection Menu =\ [ Button ( MenuFrame, text = 'Create new memory', font = ('Courier', 20), command = lambda : Raise(InputFrame) #raising a top level the input frame ), Button ( MenuFrame, text = 'Show all memories of this year\n(random order)', font = ('Courier', 14), command = lambda : [ButtonSelection(0), Raise(ViewFrame)] ), Button ( MenuFrame, text = 'Show all memories of this year\n(chronological order)', font=('Courier', 14), command = lambda : [ButtonSelection(1), Raise(ViewFrame)] ), Button ( MenuFrame, text = "See all the memories of all year\n(random order)", font=('Courier', 14), command = lambda : [ButtonSelection(2), Raise(ViewFrame)] ), Button ( MenuFrame, text = 'See all the memories of all year\n(chronological order)', font = ('Courier', 14), command = lambda: [ButtonSelection(3), Raise(ViewFrame)] ) ] #list of buttons of the menu for i in range(len(Menu)): #loop to place every button Menu[i].place\ ( anchor = 'n', #anchored at nord relx = HRel, #centered rely = 0.25 + (i * 0.125), #y position relwidth = 0.9 #% of window width )# placing the button ###############################################################################################################input InputFrame = Frame(Root) # memory insertion frame InputFrame.place(relx=0, rely=0, relwidth=1, relheight=1) #placing the input frame InputLabel = Label(InputFrame, text='Memory:', font=('Courier', 24)) #top label of input frame InputLabel.place(anchor='n', relx=HRel, relwidth=1, relheight=0.1) #placing the top label WarningLabel = Label\ ( InputFrame, text = 'attention:\ninserted memories can no longer be modified', font = ('Courier', 10), fg = '#ff0000' ) #smaller red label WarningLabel.place(anchor='n', relx=HRel, rely=0.09, relwidth=1, relheight=0.04) #placing the label MemoryInput = TextBox(InputFrame, font=('Courier', 16)) #text box for memory insertion MemoryInput.place(anchor='n', relx=HRel, rely=0.15, relwidth=0.98, relheight=0.7) #placing the textbox Submit = Button\ ( InputFrame, text = 'Create Memory', font = ('Courier', 20), command = lambda : Confirmation(InsertMemory, MemoryInput.get(1.0), Text = 'Are you sure?') ) #submition button to insert new memory Submit.place(anchor='n', relx=HRel, rely=0.8635, relwidth=0.9) #placing the button BackInput = Button\ ( InputFrame, text = 'Back to menu', font = ('Courier', 10), command = lambda : [MemoryInput.delete(1.0, 'end'), Raise(MenuFrame)] ) #return at menu button and clean the text box BackInput.place(anchor='n', relx=HRel, rely=0.945, relwidth=0.9) #placing the button ###########################################################################################################memmories MemoOpts =\ [ [True, False], #random order, last year only [False, False], #chronological order, last year only [True, True], #random order, all years [False, False] ##chronological order, all years ] #parameters for a specific query of the database MemoriesDB = lambda x: ShowMemories(MemoOpts[x][0], MemoOpts[x][ 1]) # memories of the db based on user options Sel = int() Memories = MemoriesDB(Sel) ViewFrame = Frame(Root) #memory view root frame ViewFrame.place(relx=0, rely=0, relwidth=1, relheight=1) #placing the frame in the window TopViewFrame = Frame(ViewFrame) #frame for top label and search bar TopViewFrame.place(relx=0, rely=0, relwidth=1, relheight=0.2) #placing the frame top ListFrame = Frame(ViewFrame) #canvas for memories in database ListFrame.place(relx=0, rely=0.2, relwidth=1, relheight=0.745) #placing the frame under the top frame BottomViewFrame = Frame(ViewFrame) #frame for back to menu BottomViewFrame.place(relx=0, rely=0.945, relwidth=1, relheight=0.1) #placing the frame at the bottom MemoriesLabel = Label\ ( TopViewFrame, text = 'Your Memories:', font = ('Courier', 32), ) #top label in top frame MemoriesLabel.place(anchor='n', relx=HRel, relwidth=1, relheight=0.7) #placing the label SearchBar = TextBox( TopViewFrame, font=('Courier', 16)) #search bar to search keywords in memories text SearchBar.place(anchor='n', relx=HRel, rely=0.7, relwidth=0.99, relheight=0.2) #placing the searchbar TODO SearchButton = Button\ ( TopViewFrame, text = 'Search', font = ('Courier', 14), command = lambda : None ) #botton to research SearchButton.place(anchor='n', relx=0.86, rely=0.7225, relwidth=0.25, relheight=0.17) #placingthe button SBar = Bar(ListFrame, orient='vertical') ListMemoryBox = ListBox\ ( ListFrame, selectmode = 'browse', bg = '#ffffff', activestyle = 'none', font = ('Courier', 14), selectbackground = '#e0e0e0' ) ListMemoryBox.place(anchor='n', relx=HRel, rely=0, relwidth=0.99, relheight=1) for i in ['a' for i in range(255)]: ListMemoryBox.insert('end', i) BackView = Button\ ( BottomViewFrame, text = 'Back to menu', font = ('Courier', 10), command = lambda: Raise(MenuFrame) ) #return at menu button BackView.place(anchor='n', relx=HRel, rely=0.05, relwidth=0.9) #placing the button Raise(MenuFrame) #raising the menu as first viewed frame return Root