def _show_q_or_a( a_textbox: tkinter.Text, q_textbox: tkinter.Text, q_type_checkbuttons: typing.List[tkinter.ttk.Checkbutton], q_type_indexed_q_and_a_generators: typing.Dict[ str, MM_QAndAGenerators.Q_AND_A_GENERATOR_SIGNATURE] ) -> None: if "current_q" not in _show_q_or_a.__dict__: (_show_q_or_a.current_q, _show_q_or_a.current_a) = _generate_q_and_a( q_type_checkbuttons, q_type_indexed_q_and_a_generators) _show_q_or_a.a_is_shown = False if not _show_q_or_a.a_is_shown: a_textbox.config(state="normal") a_textbox.delete("1.0", "end") a_textbox.insert("1.0", str(_show_q_or_a.current_a), "center") a_textbox.config(state="disabled") _show_q_or_a.a_is_shown = True else: (_show_q_or_a.current_q, _show_q_or_a.current_a) = _generate_q_and_a( q_type_checkbuttons, q_type_indexed_q_and_a_generators) q_textbox.config(state="normal") q_textbox.delete("1.0", "end") q_textbox.insert("1.0", _show_q_or_a.current_q, "center") q_textbox.config(state="disabled") a_textbox.config(state="normal") a_textbox.delete("1.0", "end") a_textbox.config(state="disabled") _show_q_or_a.a_is_shown = False
def listener(msgList: tkinter.Text, s: socket, clientEncryptor: PKCS1OAEP_Cipher): while True: if s.fileno() == -1: # socket closed break r, _, _ = select.select([s], [], []) for rs in r: if s == rs: try: data = rs.recv(4096) except OSError: # connection terminated (for some reason) break if not data: break msg = clientEncryptor.decrypt(data) msg = pickle.loads(msg) if msg[0]: message = "<SERVER>: " + msg[3] else: message = msg[2] + ": " + msg[3] msgList.tag_config(str(msg[1]), foreground=str(msg[1])) msgList.config(state=tkinter.NORMAL) msgList.insert(tkinter.END, message + '\n', str(msg[1])) msgList.config(state=tkinter.DISABLED)
def update(tktext: tk.Text, file: Path, parent=None) -> None: """ Replace text in open log window with (new) log file content. :param tktext: A tkinter.scrolledtext.ScrolledText or tkinter.Text insert. :param file: Path object of file from which to replace content. :param parent: The parent window over which to place messagebox; usually a Toplevel(). Defaults to app window. """ if not Path.exists(file): msg = (f'On {node()}, cannot update file:\n{file}\n' 'Was file deleted, moved or renamed?') messagebox.showerror(title='FILE NOT FOUND', detail=msg, parent=parent) return tktext.delete(tk.INSERT, tk.END) tktext.insert(tk.INSERT, Path(file).read_text()) tktext.see(tk.END) tktext.pack(fill=tk.BOTH, side=tk.LEFT, expand=True) # Need to remove focus from calling Button so can execute any # immediately following rt-click commands in parent. Use as a # precaution in case Button is not configured takefocus=False. if parent: parent.focus_set()
def status_update(status_widget: tk.Text, status_text: str): '''Append text to a status text widget. Arguments: status_widget {tk.Text} -- The status widget to send the text to. status_text {str} -- The text to append ''' status_text = '\n' + status_text status_widget.insert('end', status_text) status_widget.update_idletasks()
def insert(self, *args, **kwargs): if self["state"] == "normal": Text.insert(self, *args, **kwargs) else: self.config(state="normal") Text.insert(self, *args, **kwargs) self.config(state="disabled") if self.scrollbar.get()[1] == 1: self.see("end")
def console(text: tk.Text): """ Refreshes the logging console """ messages = rtm.get_logging_data() text.insert(tk.END, messages) if running: text.see(tk.END) text.after(INTERVAL, console, text)
def update_message_area(self, msg_area: Tk.Text, messages: List[Message]): """ Update conservation field based on the message list. """ msg_area.config(state=Tk.NORMAL) msg_area.delete("1.0", Tk.END) msg_area.insert( Tk.INSERT, "\n".join( [f"{msg.owner.name}: {msg.message_text}" for msg in messages])) msg_area.yview_moveto(1.0) msg_area.config(state=Tk.DISABLED)
def entry_to_params_to_(entry1, entry2, entry3, listbox: tk.Text): parameters = get_params(entry1.get(), entry2.get(), entry3.get()) questions = save_web_pages(parameters) with open("temp_pages.txt", "w", encoding="UTF-8") as file: for question in questions["items"]: file.write(question["link"] + "\n") with open("temp_pages.txt", "r", encoding="UTF-8") as file: listbox.delete('1.0', tk.END) text = file.readlines() for t in text: listbox.insert(tk.END, t)
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 load(self, text: tk.Text) -> None: """ Load a file :param text: The text object to load the data to :type text: tk.Text """ f = filedialog.askopenfilename(filetypes=file_extensions) if f is None: return text.delete('1.0', tk.END) with open(f, 'r', encoding="utf8") as file: text.insert('1.0', file.read()) global saved saved = True
def lade_daten_from_wowhead_by_npc(d:tk.Text, link:str): browser = webdriver.Chrome(CHROME_DRIVER_PATH) browser.get(link) loot_table = browser.find_elements_by_xpath( "//table[@class='listview-mode-default']//a[@class='q4 listview-cleartext']") boss_name:str = browser.find_element_by_xpath("//h1[@class='heading-size-1']").text zeile:int = 1 d.insert(str(zeile) + '.0', boss_name + '\n') zeile += 1 for loot in loot_table: id = __extrahiere_itemid(loot.get_attribute('href')) d.insert(str(zeile) + '.0', '['+loot.text+']' + '\t' + str(id) + '\n') zeile + 1 browser.quit()
def debug_daten(self, e: tk.EventType.ButtonPress, d: tk.Text): if len(self.tb_link_raid.get()) <= 0: self.tb_link_raid.set( 'https://canadian-crew.de/admin/manage_raids.php?s=&r=63&upd=true' ) d.insert('0.0', "[Teufelsherzhörner]\t16808\tVoltox\t25\n") d.insert('1.0', "[Zauberdolch]\t18878\tHilo\t50\n") d.insert('2.0', "[Helm des Cenarius]\t16834\tNador\t5\n") d.insert('3.0', "[Aurastein-Hammer]\t17105\tTreehugs\t75\n")
def update_textbox(self, tbox: tk.Text, words, find_indexces=None): # tBoxをにwordsで上書き tbox.delete('1.0', 'end') [tbox.insert(tk.INSERT, word) for word in words] if find_indexces: for i in find_indexces: tbox.tag_add("highlight", '{}.0'.format(i + 1), "{}.0+1lines".format(i + 1))
def insert_image_array(self, image: MyImage, text: tk.Text): """ Fill a text wigit with the contents of an image as array. """ super().clear_wigits([text]) image_as_array = np.transpose(image.modified_array) for i in image_as_array: for j in i: if j <= 9: spaces = ' ' if j > 9: spaces = ' ' if j > 99: spaces = ' ' text.insert(tk.END, str(j) + spaces) text.insert(tk.END, '\n')
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 determine_classes( file_name: str, model, textbox_classes_list: tk.Text, combobox_chosen_class: ttk.Combobox, button_save_figure: ttk.Button, button_create_heatmap: ttk.Button, ): """Fills combobox and text widget with figure classes prediction. Args: file_name (str): File name including dir, e.g. C:\\images\\penquin.jpg. model (keras.engine.training.Model): Used ML model. textbox_classes_list(tk.Text): List of predictions textbox. combobox_chosen_class(ttk.Combobox): Choose class combobox. button_save_figure(ttk.Button): Save image button. button_create_heatmap(ttk.Button): Show heatmap button. """ figure = load_image(file_name) prediction_list = get_prediction_list(figure, model) classes_for_combobox = [] global global_mapping_name_to_index textbox_classes_list.config(state=tk.NORMAL) textbox_classes_list.delete(1.0, tk.END) for figure_class in prediction_list: text_message = (f"{figure_class.order_number}. " f"class {figure_class.class_name} " f"with probability {figure_class.probability}%\n") textbox_classes_list.insert(tk.END, text_message) classes_for_combobox.append(figure_class.class_name) global_mapping_name_to_index[ figure_class.class_name] = figure_class.class_index textbox_classes_list.config(state=tk.DISABLED) combobox_chosen_class["values"] = classes_for_combobox button_save_figure.config(state=tk.DISABLED) button_create_heatmap.config(state=tk.NORMAL)
def insert_change_of_line(differences: tuple, index: int, widget: tkinter.Text, num_line: int): ''' Add one line which is changed. The reason for this function is that, when a line is totally changed, it is considered as removed; when small part is changed, the next element of differences indicates the different chars. Arguments: differences: list of differences computed with difflib. index: the index of the difference to check. widget: where to write. num_line: number of line of the index line, for font and style. Returns: A list of start-end index. ''' if index + 1 < len(differences) and differences[index + 1][0] == '?': widget.insert(tkinter.END, differences[index][2:] + '\n') for r in parse_line_index(differences[index + 1][2:]): widget.tag_add('diff', f'{num_line}.{r[0]}', f'{num_line}.{r[1]}') else: # this line should be partially changed only, mark with less distinction for safety widget.insert(tkinter.END, differences[index][2:] + '\n', 'should-partial')
def func_display(data: set, widget: tkinter.Text) -> None: widget.config(state='normal') widget.delete('1.0', tkinter.END) widget.insert(tkinter.END, '\n'.join(data)) widget.config(state='disabled')
def __format_text(text_widget: tk.Text, text: str): extracted_text, tags_dict = parse_text(text) text_widget.insert(1.0, extracted_text) for key, list_ in tags_dict.items(): for start, len_ in list_: text_widget.tag_add(key, f'1.0+{start}c', f'1.0+{start+len_}c')
def insert(self, index, text, *args): line = int(self.index(index).split(".")[0]) Text.insert(self, index, text, *args) for i in range(text.count("\n")): self.colorize(str(line+i))
def insert_text(textbox: tk.Text, text: str) -> None: textbox.configure(state="normal") textbox.insert("end", text) textbox.configure(state="disabled")
def __insert_msg(self, textbox: tk.Text, text, tag = 'msg'): textbox.configure(state = tk.NORMAL) textbox.insert(tk.END, text, tag) textbox.configure(state = tk.DISABLED)
def _fix_text_tab(self, text: tk.Text): """Change tabsize to spaces""" text.insert('insert', ' ' * 2) return 'break'
def search(self, ax: Axes, start: Point, end: Point, output: tkinter.Text) -> float: output.delete('1.0', tkinter.END) pq: VertexSearchQueue[Tuple[float, HashVertex]] = VertexSearchQueue() is_goal_reached: bool = False vi = self.closest_vertex(start) vf = self.closest_vertex(end) visited: Set[HashVertex] = set() path: List[HashVertex] = [] cost_path: float = float('Inf') cost_table = [] vi.cost_h = self.h(vi, vf) output.insert(tkinter.END, '\n' + f'initial_h: {vi.cost_h}') output.insert(tkinter.END, '\n' + f'initial: {vi.i},{vi.j} ({vi.x},{vi.y})') output.insert(tkinter.END, '\n' + f'final: {vf.i},{vf.j} ({vf.x},{vf.y})') pq.put((vi.cost_h, vi)) while not pq.empty(): v: HashVertex cost_f, v = pq.get() if v == vf: cost_path = v.cost_g is_goal_reached = True path.append(v) while v.previous is not None: path.append(v.previous) if v == vi: break v = v.previous path.reverse() break visited.add(v) cost_neighbour_pairs = self.get_cost_neighbour_pairs(v) self.draw_path_attempt(ax=ax, vertex=v) for cost_neighbour_pair in cost_neighbour_pairs: (g, vn) = cost_neighbour_pair cost_h = self.h(vn, vf) cost_g = v.cost_g + g queue_vertices = pq.vertices() if vn not in visited and vn not in queue_vertices: vn.previous = v vn.cost_g = cost_g vn.cost_h = cost_h pq.put((vn.cost_f, vn)) elif vn in queue_vertices: (cost_fn_same, vn_same) = pq.find(vn) if cost_fn_same > cost_g + cost_h: vn.previous = v vn.cost_g = cost_g vn.cost_h = cost_h pq = pq.replace(to_remove=vn, to_put=(vn.cost_f, vn)) output.insert(tkinter.END, '\n' + 'is_goal_reached: ' + str(is_goal_reached)) if is_goal_reached: path = path[path.index(vi):] for i in range(1, len(path)): self.draw_lines(ax=ax, from_vertex=path[i - 1], to_vertices=[path[i]], color='red', linewidth=2) step_cost = path[i].cost_g - path[i - 1].cost_g h_prime = path[i].cost_h h = path[i - 1].cost_h step_cost_plus_h_prime = step_cost + h_prime h_star = cost_path - path[i - 1].cost_g h_str = '{:.2f}'.format(h) h_star_str = '{:.2f}'.format(h_star) step_cost_plus_h_prime_str = '{:.2f}'.format( step_cost_plus_h_prime) cost_table.append( f'h*(n)={h_star_str}, h(n)={h_str}, h(n)<=h*(n): {h <= h_star}, c(n,n\')+h(n\')={step_cost_plus_h_prime_str}, c(n,n\')+h(n\')>=h(n): {step_cost_plus_h_prime >= h}' ) for cost_element in cost_table: output.insert(tkinter.END, '\n' + cost_element) output.see(tkinter.END) return cost_path
def write_text_and_disable(widget_txt: tk.Text, txt: str): widget_txt.configure(state=tk.NORMAL) widget_txt.delete('1.0', tk.END) widget_txt.insert(tk.END, txt) widget_txt.configure(state=tk.DISABLED)
def add_text(edit: tkinter.Text, value: str) -> None: edit.insert(tkinter.INSERT, value)
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