def config_tab_displaying(textwidget: tkinter.Text, indent_size: int, *, tag: Optional[str] = None) -> None: """Make ``textwidget`` display tabs as ``indent_size`` characters wide. For example, if ``indent_size`` is 4, then each tab character will look like be 4 spaces. This function uses the font of the textwidget, so don't change the font immediately after If ``tag`` is specified, then only the text tagged with the tag is affected, not the entire ``textwidget``. """ if tag is None: font = textwidget["font"] else: font = textwidget.tag_cget(tag, "font") or textwidget["font"] # from the text(3tk) man page: "To achieve a different standard # spacing, for example every 4 characters, simply configure the # widget with “-tabs "[expr {4 * [font measure $font 0]}] left" # -tabstyle wordprocessor”." measure_result = int(textwidget.tk.call("font", "measure", font, "0")) textwidget.config(tabs=(indent_size * measure_result, "left"), tabstyle="wordprocessor")
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 toggleText(t: tk.Text) -> str: if t[STATE] == NORMAL: t.config(state=DISABLED) elif t[STATE] == DISABLED: t.config(state=NORMAL) else: msg = f"t['state'] should be 'normal' or 'disabled', not {t[STATE]}." raise ValueError(msg) return t[STATE]
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 change_batch(widget: tkinter.Text) -> Iterator[None]: """A context manager to optimize doing many changes to a text widget. When :func:`track_changes` has been called, every change to a text widget generates a new ``<<ContentChanged>>`` event, and lots of ``<<ContentChanged>>`` events can cause Porcupine to run slowly. To avoid that, you can use this context manager during the changes, like this:: with textwidget.change_batch(some_text_widget_with_change_tracking): for thing in big_list_of_things_to_do: textwidget.delete(...) textwidget.insert(...) This context manager also affects some other things, and so it can be useful even with text widgets that don't use :func:`track_changes`: * Undoing the whole batch is done with one Ctrl+Z press. * When the ``with`` statement ends, the cursor is moved back to where it was when the ``with`` statement started. See :source:`porcupine/plugins/indent_block.py` for a complete example. """ cursor_pos = widget.index("insert") autoseparators_value = widget["autoseparators"] try: widget.config(autoseparators=False) widget.edit_separator() try: tracker = _change_trackers[widget] except KeyError: yield else: tracker.begin_batch() try: yield finally: tracker.finish_batch() widget.edit_separator() finally: widget.config(autoseparators=autoseparators_value) widget.mark_set("insert", cursor_pos)
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')
class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def generate(self): n = int(self.menu_gen.get()) seed = self.inp_seed.get() self.output = Generator.convert(seed, n) if len(self.output) > 0: self.generated = True self.butt_draw.config( state= 'normal') self.chek_fullscrn.config(state= 'normal') self.clearOutput(self.output) def draw(self, n, step=False): p1, p2 = Draw.move(n) self.curr_canvas.create_line(p1[0], p1[1], p2[0], p2[1], fill= self.color, width= self.thick) if step: self.curr_canvas.update_idletasks() def do(self, action, step, rainbow): if len(action) > 1: p = action[1] else: p = 1.0 self.timebuff += step cmd = action[0].lower() if cmd == "draw": if rainbow: self.incColor() if self.incThickYN: self.incThick(self.reverseThick, False) elif self.incThickYN: self.incThick(self.reverseThick, True) if self.timebuff > 1.0: truncate = int(self.timebuff) self.after(truncate, self.draw(float(p), True)) self.timebuff -= truncate else: self.draw(float(p)) elif cmd == "turn": Draw.turn(float(p)) elif cmd == "skip": Draw.skip(float(p)) elif cmd == "back": Draw.back(float(p)) elif cmd == "color": if not rainbow: self.color = Color.getHexString(p) elif cmd == "thick": self.thick = int(p) else: print("Unknown command " + cmd) def drawAll(self, newWindow= True): if self.generated == True: self.butt_print.config(state= 'disabled') self.timebuff = 0.0 self.color = Color.white() self.thick = 2 l = float(self.slid_linesize.get()) a = float(self.slid_angle.get()) Draw.init(self.startingPoint, l, a) if self.fullScreen.get() == 1: if newWindow: self.curr_canvas = dc.BigCanvas(self).canvas self.canvas.delete("all") else: self.curr_canvas = self.canvas self.curr_canvas.delete("all") self.curr_canvas.config(bg= Color.getHexString(self.bgColor.get())) rainbow = self.rainbowCheck.get() == 1 if rainbow or self.incThickYN: self.incStep = 1.0/float(self.getDrawCount(self.output)) self.percent = 0.0 for c in self.output: if c == '[': Draw.push() elif c == ']': Draw.pop() else: for r in Rule.getDrawings(): if c == r[0]: if len(r) > 2: params = (r[1], r[2]) else: params = (r[1],) s = float(self.slid_timer.get()) self.do(params, s, rainbow) break self.butt_print.config(state= 'normal') def incColor(self): self.color = Color.getValueByPercent(self.percent) self.percent += self.incStep def incThick(self, reverse, incYN): maxthick = 5 minthick = 1 diff = maxthick - minthick if reverse: result = maxthick - int(diff * self.percent) else: result = minthick + int(diff * self.percent) self.thick = result if incYN: self.percent += self.incStep def getDrawCount(self, s): draw_commands = [] for r in Rule.getDrawings(): if r[1].lower() == "draw": draw_commands.append(r[0]) draw_count = 0; for c in s: for d in draw_commands: if c == d: draw_count += 1 break return draw_count def clearOutput(self, replacement=None): self.text_output.config(state= 'normal') self.text_output.delete(1.0, END) if replacement: self.text_output.insert(END, replacement) self.text_output.config(state= 'disabled') def formatRules(self, rules): ret = [] for r in rules: entry = r[0] + " | " + r[1] if len(r) > 2: entry += " " + r[2] ret.append(entry) return ret def getRuleFromFormatted(self, s): if s: rule = s.split('|') rule[0] = rule[0].strip() rule[1] = rule[1].strip() prod = rule[1].split(" ") if len(prod) == 1: return (rule[0], prod[0]) else: return (rule[0], prod[0], prod[1]) def RefreshLists(self): self.list_prod.delete(0, END) self.list_draw.delete(0, END) l = self.formatRules(Rule.getProductions()) for p in l: self.list_prod.insert(END, p) l = self.formatRules(Rule.getDrawings()) for d in l: self.list_draw.insert(END, d) def AddProductionRule(self, edit=None): rule = dp.AddProductionRuleDialog(self, edit).result if rule: if edit: Rule.removeProd(edit[0]) Rule.AddProduction(rule) self.RefreshLists() def AddDrawingRule(self, edit=None): rule = dd.AddDrawingRuleDialog(self, edit).result if rule: if edit: Rule.removeDraw(edit[0]) Rule.AddDrawing(rule) self.RefreshLists() def EditProductionRule(self): s = self.list_prod.curselection() if s: idx = s[0] rule = (idx,) + self.getRuleFromFormatted(self.list_prod.get(idx)) if rule: self.AddProductionRule(rule) def EditDrawingRule(self): s = self.list_draw.curselection() if s: idx = s[0] rule = (idx,) + self.getRuleFromFormatted(self.list_draw.get(idx)) if rule: self.AddDrawingRule(rule) def DeleteProductionRule(self): s = self.list_prod.curselection() if s: Rule.removeProd(s[0]) self.RefreshLists() def DeleteDrawingRule(self): s = self.list_draw.curselection() if s: Rule.removeDraw(s[0]) self.RefreshLists() def packOutput(self): ret = "" ret += self.packAxiom() ret += self.packProdRules() ret += self.packDrawRules() return ret def packAxiom(self): return "@" + str(self.inp_seed.get()).strip() def packRules(self, rules): ret = "@" for r in rules: ret += "$" + str(r[0]) + "|" + str(r[1]) if len(r) > 2: ret += ":" + str(r[2]) return ret def packProdRules(self): return self.packRules(Rule.getProductions()) def packDrawRules(self): return self.packRules(Rule.getDrawings()) def parseProdRules(self, raw): rules = raw.split('$') for rule in rules: if rule is not "": r = rule.split('|') Rule.AddProduction((r[0], r[1])) def parseDrawRules(self, raw): rules = raw.split('$') for rule in rules: if rule is not "": r = rule.split('|') p = r[1].split(':') if len(p) == 1: tup = (r[0], p[0]) else: tup = (r[0], p[0], p[1]) Rule.AddDrawing(tup) def parseSaveFile(self, s): Rule.wipe() settings = s.split('@') self.inp_seed.set(str(settings[1])) self.parseProdRules(settings[2]) self.parseDrawRules(settings[3]) self.RefreshLists() def save(self): try: filename = filedialog.asksaveasfilename(**self.file_options['txt']) if filename: f = open(filename, 'w') f.write(self.packOutput()) f.close() except Exception as e: print("File IO error in save\n", e) def load(self): try: filename = filedialog.askopenfilename(**self.file_options['txt']) if filename: f = open(filename, 'r') self.parseSaveFile(f.read()) f.close() self.slid_linesize.set(1.0) self.slid_timer.set(0.0) self.menu_gen.set(1) self.clearOutput() except Exception as e: print("File IO error in load\n" + e) def help(self): help.HelpDialog(self) def saveImage(self): filename = filedialog.asksaveasfilename(**self.file_options['ps']) self.curr_canvas.postscript(file=filename, colormode='color') def click(self, event): self.startingPoint = (event.x, event.y) def clickAndRedraw(self, event): self.click(event) self.drawAll(False) def fileOptions(self): self.file_options = {} txt_options = {} ps_options = {} txt_options['defaultextension'] = '.txt' txt_options['filetypes'] = [('Plaintext', '.txt')] txt_options['initialdir'] = 'Patterns' ps_options['defaultextension'] = '.ps' ps_options['filetypes'] = [('Postscript Image', '.ps')] ps_options['initialdir'] = 'Images' self.file_options['txt'] = txt_options self.file_options['ps'] = ps_options def makeMenuBar(self): self.menubar = Menu(self); self.menubar.add_command(label="Save", command= self.save) self.menubar.add_command(label="Load", command= self.load) self.menubar.add_command(label="Help", command= self.help) root.config(menu= self.menubar) def makeInputFrame(self): self.inp_seed = String() self.bgColor = String() self.gen_value = Int() self.rainbowCheck = Int() self.fram_input = Frame(self, bd= 2, relief= self.style, width= input_frame_width, height= input_frame_height) self.fram_seed = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_prod = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_draw = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_drawParams = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_gen = Frame(self.fram_input, bd= 1, relief= self.style) self.fram_output = Frame(self.fram_input, bd= 1, relief= self.style) self.menu_gen = DropDown(self.fram_gen, textvariable= self.gen_value, state= 'readonly') self.entr_seed = Input(self.fram_seed, textvariable= self.inp_seed) self.text_output = Output(self.fram_output, width= 35, height= 10) self.scrl_output = Scrollbar(self.fram_output) self.list_prod = List(self.fram_prod, selectmode= BROWSE, font= "Courier 8", height= 5) self.list_draw = List(self.fram_draw, selectmode= BROWSE, font= "Courier 8", height= 5) self.slid_linesize = Slider(self.fram_drawParams, from_= 0.1, to= 10.0, orient= HORIZONTAL, resolution= 0.1, length= 180) self.slid_timer = Slider(self.fram_drawParams, from_= 0, to= 2, orient= HORIZONTAL, resolution= 0.02, length= 180) self.slid_angle = Slider(self.fram_drawParams, from_= 0, to= 359, orient= HORIZONTAL, length= 180) self.entr_bgcolor = Input (self.fram_drawParams, textvariable= self.bgColor) self.butt_prodAdd = Button(self.fram_prod, text= "Add", width=8, command= self.AddProductionRule) self.butt_prodEdit = Button(self.fram_prod, text= "Edit", width=8, command= self.EditProductionRule) self.butt_prodDelete = Button(self.fram_prod, text= "Delete", width=8, command= self.DeleteProductionRule) self.butt_drawAdd = Button(self.fram_draw, text= "Add", width=8, command= self.AddDrawingRule) self.butt_drawEdit = Button(self.fram_draw, text= "Edit", width=8, command= self.EditDrawingRule) self.butt_drawDelete = Button(self.fram_draw, text= "Delete", width=8, command= self.DeleteDrawingRule) self.chek_incColor = CheckBox(self.fram_draw, text= "Rainbow", variable= self.rainbowCheck) Label(self.fram_seed, text= "Axiom:", width=8).grid (row=0, column=0) Label(self.fram_prod, text= "Production\nRules:", width=8).grid (row=0, column=0) Label(self.fram_draw, text= "Drawing\nRules:", width=8).grid (row=0, column=0) Label(self.fram_drawParams, text= "Line Size:").grid (row=0, column=0) Label(self.fram_drawParams, text= "Delay (ms):").grid (row=1, column=0) Label(self.fram_drawParams, text= "Starting Angle:").grid (row=2, column=0) Label(self.fram_drawParams, text= "Background Color:").grid (row=3, column=0) Label(self.fram_output, text= "Output:").grid (row=0, column=0) Label(self.fram_gen, text= "Generations:").grid (row=0, column=0) self.gen_value.set(1) self.menu_gen['values'] = tuple(range(1, 13)) self.slid_linesize.set(1.0) self.bgColor.set( Color.default() ) self.text_output.config(state='disabled', yscrollcommand= self.scrl_output.set) self.scrl_output.config(command=self.text_output.yview) self.fram_input.grid (row=0, column=0) self.fram_seed.grid (row=1, column=0, sticky= 'ew') self.fram_prod.grid (row=2, column=0, sticky= 'ew') self.fram_draw.grid (row=3, column=0, sticky= 'ew') self.fram_drawParams.grid (row=4, column=0, sticky= 'ew') self.fram_gen.grid (row=5, column=0, sticky= 'ew') self.fram_output.grid (row=6, column=0, sticky= 'ew') self.entr_seed.grid (row=0, column=1, sticky= 'ew') self.list_prod.grid (row=0, column=1, sticky= 'ew') self.butt_prodAdd.grid (row=1, column=0, sticky= 'ew') self.butt_prodEdit.grid (row=1, column=1, sticky= 'ew') self.butt_prodDelete.grid (row=1, column=2, sticky= 'ew') self.list_draw.grid (row=0, column=1) self.butt_drawAdd.grid (row=1, column=0, sticky= 'ew') self.butt_drawEdit.grid (row=1, column=1, sticky= 'ew') self.butt_drawDelete.grid (row=1, column=2, sticky= 'ew') self.chek_incColor.grid (row=0, column=2) self.slid_linesize.grid (row=0, column=1, sticky= 'ew') self.slid_timer.grid (row=1, column=1, sticky= 'ew') self.slid_angle.grid (row=2, column=1, sticky= 'ew') self.entr_bgcolor.grid (row=3, column=1, sticky= 'ew') self.menu_gen.grid (row=0, column=1, sticky= 'ew') self.text_output.grid (row=1, column=0) self.scrl_output.grid (row=1, column=1, sticky= 'ns') def makeCanvasFrame(self): self.fram_canvas = Frame(self, bd=10, relief=self.style) self.canvas = Canvas(self.fram_canvas, width= canvas_width, height= canvas_height) self.fram_canvas.grid(row=0, column=1, sticky='nesw') self.canvas.grid(sticky='nesw') self.canvas.bind("<Button-1>", self.click) self.curr_canvas = self.canvas def makeIgnitionFrame(self): self.fullScreen = Int() self.fram_ignition = Frame(self, bd=4, relief=self.style, width= ignition_frame_width, height= ignition_frame_height) self.butt_generate = Button(self.fram_ignition, text= " -- GENERATE -- ", width=111, command= self.generate) self.butt_draw = Button(self.fram_ignition, text= " -- DRAW -- ", width=100, command= self.drawAll, state= 'disabled') self.butt_print = Button(self.fram_ignition, text= "Save Image", command= self.saveImage, state= 'disabled') self.chek_fullscrn = CheckBox(self.fram_ignition, text= "Fullscreen", variable= self.fullScreen, state= 'disabled') self.fram_ignition.grid(row=1, column=0, columnspan=2) self.butt_generate.grid(row=0, column=0, columnspan=2) self.butt_draw.grid( row=1, column=0) self.butt_print.grid( row=0, column=2, rowspan= 2, sticky='ns') self.chek_fullscrn.grid(row=1, column=1) def createWidgets(self): self.incThickYN = False self.reverseThick = False self.style = RIDGE self.startingPoint = (20, 20) self.generated = False self.fileOptions() self.makeMenuBar() self.makeInputFrame() self.makeCanvasFrame() self.makeIgnitionFrame()
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 disable(self, disable): Text.config(self, state=DISABLED if disable else NORMAL)
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