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 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 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 delete(self, *args, **kwargs): if self["state"] == "normal": Text.delete(self, *args, **kwargs) else: self.configure(state="normal") Text.delete(self, *args, **kwargs) self.configure(state="disabled")
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 new(self, text: tk.Text, data: str) -> None: """ Create a new document after saving :param text: The text ui element :param data: Text inside the ui :type text: tk.Text :type data: str """ self.check_save(data) text.delete('1.0', tk.END)
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 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 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 erase(file: Path, tktext: tk.Text, parent=None) -> None: """ Delete file contents and its displayed window text. :param file: Path object of file from which to erase content. :param tktext: A tkinter.ScrolledText or tkinter.Text insert. :param parent: The parent window over which to place messagebox, usually the *tktext* Toplevel. Defaults to root as parent window. """ if not Path.exists(file): info = (f'On {node()}, could not erase contents of\n' f'{file}\nbecause file is missing.\n' 'Was it deleted, moved or renamed?') messagebox.showerror(title='FILE NOT FOUND', detail=info, parent=parent) # Need to remove focus from calling Button so can execute any # immediately following rt-click commands in parent. if parent: parent.focus_set() return if platform[:3] == 'dar': msgdetail = (f"'Enter/Return' will also delete " f"content of file {file}.") else: msgdetail = (f"'Enter/Return' or space bar will also delete " f"content of file {file}.") okay = messagebox.askokcancel(title='Confirmation needed', message='Delete file content?', detail=msgdetail, parent=parent) if okay: try: with open(file, 'w') as _f: _f.close() tktext.delete('1.0', tk.END) if parent: parent.focus_set() except PermissionError: info = (f'On {node()}, could not erase contents of\n' f'{file}\nbecause it could not be opened.') messagebox.showerror(title='FILE PERMISSION ERROR', detail=info, parent=parent)
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 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 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 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
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 __init__(self, master:tk.Text=None, cnf={}, **kw): super().__init__(master, cnf, **kw) self.add_command(label='Clear log', command=lambda: master.delete('1.0', tk.END))
def clear_selected_text(t: tk.Text) -> None: try: t.delete(tk.SEL_FIRST, tk.SEL_LAST) except tk.TclError: print("> Nothing selected!")
def clear_text(t: tk.Text) -> None: t.delete("1.0", tk.END)
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 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