def token(self, tok): font = get_font(self.size, self.weight, self.style) if isinstance(tok, Text): for word in tok.text.split(): w = font.measure(word) if self.cursor_x + w > WIDTH - HSTEP: self.cursor_y += font.metrics("linespace") * 1.25 self.cursor_x = HSTEP self.display_list.append( (self.cursor_x, self.cursor_y, word, font)) self.cursor_x += w + font.measure(" ") elif tok.tag == "i": self.style = "italic" elif tok.tag == "/i": self.style = "roman" elif tok.tag == "b": self.weight = "bold" elif tok.tag == "/b": self.weight = "normal" elif tok.tag == "small": self.size -= 2 elif tok.tag == "/small": self.size += 2 elif tok.tag == "big": self.size += 4 elif tok.tag == "/big": self.size -= 4 elif tok.tag == "br": self.flush() elif tok.tag == "/p": self.flush() self.cursor_y += VSTEP # elif tok.tag == "h1": # self.size = 30 # elif tok.tag == "h2": # self.size = 26 # elif tok.tag == "h3": # self.size = 24 # elif tok.tag == "h4": # self.size = 18 elif tok.tag == "/blockqoute": self.flush() self.cursor_y += VSTEP elif tok.tag == "/h1": self.size = 16 self.flush() self.cursor_y += VSTEP elif tok.tag == "/h2": self.size = 16 self.flush() self.cursor_y += VSTEP elif tok.tag == "/h3": self.size = 16 self.flush() self.cursor_y += VSTEP elif tok.tag == "/h4": self.size = 16 self.flush() self.cursor_y += VSTEP
def text(self, text, offset=(0, 0), horiz=base.Renderer.LEFT, vert=base.Renderer.BOTTOM, *, angle=None, font=None, colour, width=None): anchors = { (self.TOP, self.LEFT): tkinter.NW, (self.TOP, self.CENTRE): tkinter.N, (self.TOP, self.RIGHT): tkinter.NE, (self.CENTRE, self.LEFT): tkinter.W, (self.CENTRE, self.CENTRE): tkinter.CENTER, (self.CENTRE, self.RIGHT): tkinter.E, (self.BOTTOM, self.LEFT): tkinter.SW, (self.BOTTOM, self.CENTRE): tkinter.S, (self.BOTTOM, self.RIGHT): tkinter.SE, } kw = dict() if angle is not None: kw.update(angle=angle) if font is None: font = self.defaultfont else: font = self.fonts[font] kw.update(font=font) colour = self._colour(colour) kw.update(fill=colour) (ox, oy) = offset ox *= self.scaling[0] oy *= self.scaling[1] if isinstance(text, str): kw.update(anchor=anchors[(vert, horiz)]) if width is not None: kw.update(width=width * self.scaling[0]) self.canvas.create_text(ox, oy, text=text, **kw) return length = sum(font.measure(seg["text"]) for seg in text) anchor = anchors[(vert, self.LEFT)] anchors = {self.LEFT: 0, self.CENTRE: 0.5, self.RIGHT: 1} pos = -length * anchors[horiz] (cos, sin) = self._rotation(angle or 0) for seg in text: x = ox + pos * cos y = oy + pos * sin text = seg["text"] self.canvas.create_text(x, y, text=text, anchor=anchor, **kw) newpos = pos + font.measure(text) if seg.get("overline"): linespace = font.metrics("linespace") anchors = {self.TOP: 0, self.CENTRE: 0.5, self.RIGHT: 1} linespace *= anchors[vert] dx = +linespace * sin dy = -linespace * cos nx = ox + dx + newpos * cos ny = oy + dy + newpos * sin self.canvas.create_line(x + dx, y + dy, nx, ny, fill=colour) pos = newpos
def text(self, node): font = self.font(node) for word in node.text.split(): w = font.measure(word) if self.cx + w > WIDTH - HSTEP: self.flush() self.line.append((self.cx, word, font)) self.cx += w + font.measure(" ")
def set_by_click(self, x: int, font: tk.font.Font): self.position = 0 if not self.text or x < font.measure(self.text[0]): return while self.position < len(self.text) and x > font.measure( self.text[:self.position + 1]): self.position += 1
def text(self, text): if any([ord(c) >= 65536 for c in text]): return font = tkinter.font.Font(family=FONT_FAMILY, size=self.fontsize, weight=self.weight, slant=self.style) for word in text.split(): w = font.measure(word) if self.cursor_x + w >= self.width - MARGIN: self.flush() self.line.append((self.cursor_x, word, font)) self.cursor_x += w + font.measure(" ")
def text(self, text): font = tkinter.font.Font( size=self.size, weight=self.weight, slant=self.style, ) for word in text.split(): w = font.measure(word) if self.cursor_x + w > WIDTH - HSTEP: self.flush() self.line.append((self.cursor_x, word, font)) self.cursor_x += w + font.measure(" ")
def text(self, node): color = node.style["color"] weight = node.style["font-weight"] style = node.style["font-style"] if style == "normal": style = "roman" size = int(float(node.style["font-size"][:-2]) * .75) font = get_font(size, weight, style) for word in node.text.split(): w = font.measure(word) if self.cursor_x + w > self.x + self.width: self.flush() self.line.append((self.cursor_x, word, font, color)) self.cursor_x += w + font.measure(" ")
def __init__(self, x1, y1, text, font, color): self.x1 = x1 self.y1 = y1 self.text = text self.font = font self.color = color self.y2 = y1 + font.measure("linespace")
def layout(tokens): display_list = [] fonts = { # (bold, italic) -> font (False, False): tkinter.font.Font(family="Times", size=16), (True, False): tkinter.font.Font(family="Times", size=16, weight="bold"), (False, True): tkinter.font.Font(family="Times", size=16, slant="italic"), (True, True): tkinter.font.Font(family="Times", size=16, weight="bold", slant="italic"), } x, y = 13, 13 bold, italic = False, False terminal_space = True for tok in tokens: font = fonts[bold, italic] if isinstance(tok, Text): if tok.text[0].isspace() and not terminal_space: x += font.measure(" ") words = tok.text.split() for i, word in enumerate(words): w = font.measure(word) if x + w > 787: x = 13 y += font.metrics('linespace') * 1.2 display_list.append((x, y, word, font)) x += w + (0 if i == len(words) - 1 else font.measure(" ")) terminal_space = tok.text[-1].isspace() if terminal_space and words: x += font.measure(" ") elif isinstance(tok, Tag): if tok.tag == "i": italic = True elif tok.tag == "/i": italic = False elif tok.tag == "b": bold = True elif tok.tag == "/b": bold = False elif tok.tag == "/p": terminal_space = True x = 13 y += font.metrics("linespace") * 1.2 + 16 return display_list
def guess_size(display_string, bounding_width, bounding_height, rel_size=0): no_lines = display_string.count("\n") + 1 size_guess = bounding_height // ((3 - rel_size) * no_lines) font = tkinter.font.Font(size=size_guess) text_width = font.measure(display_string) if text_width > bounding_width: font_size = size_guess * bounding_width // text_width else: font_size = size_guess return font_size
def guess_size(display_string, bounding_width, bounding_height, rel_size=0): no_lines = display_string.count("\n") + 1 size_guess = bounding_height // ((3-rel_size) * no_lines) font = tkinter.font.Font(size=size_guess) text_width = font.measure(display_string) if text_width > bounding_width: font_size = size_guess * bounding_width // text_width else: font_size = size_guess return font_size
def text(self, node): font = self.font() if node.text[0].isspace() and not self.terminal_space: self.x += font.measure(" ") words = node.text.split() for i, word in enumerate(words): w = font.measure(word) if self.x + w > self.parent.content_left( ) + self.parent.content_width(): self.x = self.parent.content_left() self.y += font.metrics('linespace') * 1.2 self.dl.append(DrawText(self.x, self.y, word, font)) self.x += w + (0 if i == len(words) - 1 else font.measure(" ")) self.terminal_space = node.text[-1].isspace() if self.terminal_space and words: self.x += font.measure(" ")
def calenderConfig(self): cols = self.cal.formatweekheader(3).split() self.calenderMainView['columns'] = cols self.calenderMainView.tag_configure('header',background='grey90') self.calenderMainView.insert('','end', values=cols, tag='header') font = tkinter.font.Font() maxwidth = max(font.measure(col) for col in cols)*5 for col in cols: self.calenderMainView.column(col, width=maxwidth, minwidth=maxwidth, anchor='c')
def adjust(self): ref = 0 car_width = 0 measuring = dict() for key, value in self.buttons.items(): style = value['style'] font = self.root.font1 measure = font.measure(key) ref = max(measure, ref) measuring[key] = measure return measuring, ref
def __config_calendar(self): cols = self._cal.formatweekheader(3).split() self._calendar['columns'] = cols self._calendar.tag_configure('header', background='grey90') self._calendar.insert('', 'end', values=cols, tag='header') # adjust its columns width font = tkinter.font.Font() maxwidth = max(font.measure(col) for col in cols) for col in cols: self._calendar.column(col, width=maxwidth, minwidth=maxwidth, anchor='e')
def __config_calendar(self): cols = self._cal.formatweekheader(3).split() self._calendar['columns'] = cols self._calendar.tag_configure('header' , background='grey90') self._calendar.insert('' , 'end' , values=cols , tag='header') # adjust its columns width font = tkinter.font.Font() maxwidth = max(font.measure(col) for col in cols) for col in cols: self._calendar.column(col , width=maxwidth , minwidth=maxwidth , anchor='e')
def __config_calendar(self): cols = self._cal.formatweekheader(3).split() self._calendar["columns"] = cols self._calendar.tag_configure("header", background="grey90") self._calendar.insert("", "end", values=cols, tag="header") # adjust its columns width font = tk.font.Font() maxwidth = max(font.measure(col) for col in cols) for col in cols: self._calendar.column(col, width=maxwidth, minwidth=maxwidth, anchor="e")
def adjust(self): ref = 0 car_width = 0 measuring = dict() for key, value in self.profiles.items(): style = value['style'] font = self.root.font1 measure = font.measure(key) ref = max(measure, ref) measuring[key] = measure for key, button in self.profiles.items(): button['text'] = key + ( (ref - measuring[key]) // self.root.car_width + 1) * ' '
def layout_text(node, state): x, y, bold, italic, terminal_space, display_list = state font = tkinter.font.Font(family="Times", size=16, weight="bold" if bold else "normal", slant="italic" if italic else "roman") if node.text[0].isspace() and not terminal_space: x += font.measure(" ") words = node.text.split() for i, word in enumerate(words): w = font.measure(word) if x + w > 787: x = 13 y += font.metrics('linespace') * 1.2 display_list.append((x, y, word, font)) x += w + (0 if i == len(words) - 1 else font.measure(" ")) terminal_space = node.text[-1].isspace() if terminal_space and words: x += font.measure(" ") return x, y, bold, italic, terminal_space, display_list
def text(self, text, window_width): font = tkinter.font.Font(size=self.font_size, weight=self.weight, slant=self.style) # Calculate entire line's width if (self.should_center): line_width = sum([font.measure(word) for word in text.split()]) for word in text.split(): w = font.measure(word) # FIXME: This will break when the line_width exceeds window width. # Write a way to break words and center in this case. if (self.should_center): self.cursor_x = int(window_width / 2) - int(line_width / 2) self.should_center = False if self.cursor_x + w >= window_width - self.HSTEP: self.flush() self.line.append((self.cursor_x, word, font)) self.cursor_x += w + font.measure(" ")
def __init__(self, terminal=None): self.fg='#%02x%02x%02x' % TEXT_COLOR bg='#%02x%02x%02x' % background_color() self.terminal = terminal self.root = tkinter.Tk() if 'Teleprinter' in tkinter.font.families(self.root): # http://www.zanzig.com/download/ font = tkinter.font.Font(family='Teleprinter').actual() font['weight'] = 'bold' elif 'TELETYPE 1945-1985' in tkinter.font.families(self.root): # https://www.dafont.com/teletype-1945-1985.font font = tkinter.font.Font(family='TELETYPE 1945-1985').actual() else: font = tkinter.font.nametofont('TkFixedFont').actual() font['size'] = 16 font = tkinter.font.Font(**font) self.font = font self.font_width = font.measure('X') self.font_height = self.font_width * 10 / 6 self.canvas = tkinter.Canvas( self.root, bg=bg, height=24 * self.font_height + SLOP*2, width=COLUMNS * self.font_width + SLOP*2) bbox = (0, 0, self.font_width, self.font_height) self.cursor_id = self.canvas.create_rectangle(bbox) self.root.bind('<Key>', self.key) xscrollbar = tkinter.Scrollbar(self.root, orient='horizontal') xscrollbar.grid(row=1, column=0, sticky='ew') yscrollbar = tkinter.Scrollbar(self.root) yscrollbar.grid(row=0, column=1, sticky='ns') self.canvas.grid(row=0, column=0, sticky='nsew') self.root.grid_rowconfigure(0, weight=1) self.root.grid_columnconfigure(0, weight=1) self.max_line = 0 self.canvas.config( xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set, offset='%d,%d'%(-SLOP,-SLOP), scrollregion=(-SLOP, -SLOP, COLUMNS*self.font_width+SLOP, self.font_height+SLOP), ) xscrollbar.config(command=self.canvas.xview) yscrollbar.config(command=self.canvas.yview)
def render(self): self.canvas.delete("all") for cmd in self.display_list: if cmd.y1 > self.scroll + HEIGHT - 60: continue if cmd.y2 < self.scroll: continue cmd.draw(self.scroll - 60, self.canvas) self.canvas.create_rectangle(0, 0, 800, 60, width=0, fill='light gray') self.canvas.create_rectangle(50, 10, 790, 50) font = tkinter.font.Font(family="Courier", size=30) self.canvas.create_text(55, 15, anchor='nw', text=self.address_bar, font=font) self.canvas.create_rectangle(10, 10, 35, 50) self.canvas.create_polygon(15, 30, 30, 15, 30, 45, fill='black') if self.focus == "address bar": w = font.measure(self.address_bar) self.canvas.create_line(55 + w, 15, 55 + w, 45)
def init_add_reminder_ui(): global canvas, width, height, font canvas = tk.Canvas(root, bg=color, width=width, height=height, highlightthickness=0) canvas.pack() reminder_string = "add a reminder" t_width_px = font.measure(reminder_string) t_height_px = (72 * 4) // 3 t_x = (width // 2) - (t_width_px / 2) t_y = (height * (1 / 5)) - (t_height_px / 2) t_width_px += 40 t_height_px += 40 t_x -= 20 t_y -= 20 canvas.create_round_rectangle(t_x - 10, t_y - 10, t_width_px + 20, 400, r=10, fill="#2226DD") canvas.create_round_rectangle(t_x, t_y, t_width_px, t_height_px, r=10, fill="#2284DD") canvas.create_text((width // 2, height * (1 / 5)), text=reminder_string, font=font, fill="#2226DD") text_rows = [["description"], ["00:00", "AM", "01", "Jan", "0000"], ["Remind me", "5 min", "before"]] writable = [[True], [True, True, True, True, True], [False, True, False]]
def render(self): self.timer.start("Rendering") self.canvas.delete("all") for cmd in self.display_list: if cmd.y1 > self.scroll + HEIGHT - 60: continue if cmd.y2 < self.scroll: continue cmd.draw(self.scroll - 60, self.canvas) self.timer.start("Chrome") self.canvas.create_rectangle(0, 0, 800, 60, width=0, fill='light gray') self.canvas.create_rectangle(50, 10, 790, 50) font = tkinter.font.Font(family="Courier", size=30) self.canvas.create_text(55, 15, anchor='nw', text=self.address_bar, font=font) self.canvas.create_rectangle(10, 10, 35, 50) self.canvas.create_polygon(15, 30, 30, 15, 30, 45, fill='black') if self.focus == "address bar": w = font.measure(self.address_bar) self.canvas.create_line(55 + w, 15, 55 + w, 45) elif isinstance(self.focus, InputLayout): text = self.focus.node.attributes.get("value", "") x = self.focus.x + self.focus.font.measure(text) y = self.focus.y - self.scroll + 60 self.canvas.create_line(x, y, x, y + self.focus.h) self.timer.stop()
def width( self, font, index ): ''' params: tk font object, Option index return: width in pixels ''' return font.measure( self.displayItems[index] )
chars.append(0x0456) chars.append(0x0457) chars.append(0x2015) chars.append(0x2026) chars.append(0x2103) chars.append(0x2109) chars.append(0x2116) out = codecs.open("fnt.txt", 'w', "utf-8") minWidth = 1e6 maxWidth = 0 out.write("CHARWIDTH_MM_PER_POINT = {\n") out.write(" '\\r': 0,\n") out.write(" '\\n': 0,\n") for char in chars: width = font.measure(chr(char)) * mm_per_pix / 100 if minWidth > width: minWidth = width if maxWidth < width: maxWidth = width if char in (0x0027, 0x005c): out.write(" '\\{}': {},\n".format(chr(char), width)) else: out.write(" '{}': {},\n".format(chr(char), width)) out.write(' "min": {},\n'.format(minWidth)) out.write(' "max": {},\n'.format(maxWidth)) out.write('}\n') out.close() root.destroy()
def createText(r, anchor, text, font): if font.measure(text) < r.getWidth(): canvas.create_text(r.pos(tk.N if anchor == tk.CENTER else tk.NW), anchor=anchor, text=text, state='disabled', font=font)
def get_text_size(text): font = UnscaledFont return font.measure(text), font.metrics("linespace")
def get_text_size(text, font_size): tkinter.Frame().destroy() font = tkinter.font.Font(family='Helvetica Neue', size=font_size) return (font.measure(text) + 10, font.metrics('linespace'))
def layout(tokens): display_list = [] x, y = 13, 13 bold, italic, uline = False, False, False family, size, color = "Times", 16, "black" pre = False terminal_space = True for tok in tokens: font = tkinter.font.Font(family=family, size=size, weight=("bold" if bold else "normal"), slant=("italic" if italic else "roman")) if isinstance(tok, Text): if tok.text[0].isspace() and not pre and not terminal_space: x += font.measure(" ") words = tok.text.split("\n") if pre else tok.text.split() for i, word in enumerate(words): w = font.measure(word) if x + w > 787 and not pre: x = 13 y += font.metrics('linespace') * 1.2 display_list.append(DL.Text(word, x, y, font, color)) if uline: yl = y + font.metrics("ascent") + 1 display_list.append(DL.Line(x, yl, x + w, yl, color)) if pre: if i == len(words) - 1: x += w else: x = 13 y += font.metrics("linespace") * 1.2 else: x += w + (0 if i == len(words) - 1 else font.measure(" ")) terminal_space = tok.text[-1].isspace() if terminal_space and words and not pre: x += font.measure(" ") elif isinstance(tok, Tag): if tok.tag == "i": italic = True elif tok.tag == "/i": italic = False elif tok.tag == "b": bold = True elif tok.tag == "/b": bold = False elif tok.tag == "pre": family = "Courier New" pre = True elif tok.tag == "/pre": family = "Times" pre = False terminal_space = True x = 13 y += font.metrics("linespace") * 1.2 + 16 elif tok.tag == "a": color = "blue" uline = True elif tok.tag == "/a": color = "black" uline = False elif tok.tag == "h1": # Exercise 1 bold = True elif tok.tag == "/h1": bold = False terminal_space = True x = 13 y += font.metrics("linespace") * 1.2 + 16 elif tok.tag == "/p": terminal_space = True x = 13 y += font.metrics("linespace") * 1.2 + 16 return display_list
#Frame for output section F2_right = Frame(F2, relief=SUNKEN, borderwidth=2) F2_right.pack(side=RIGHT, fill=BOTH) lb_in = Label(F2_left, padx=10, text="Input", font=Bfont) lb_out = Label(F2_right, padx=10, text="Output", font=Bfont) lb_in.pack(anchor='w') lb_out.pack(anchor='w') b = Scrollbar(master=F2_left, orient='vertical') b.pack(side=RIGHT, fill=Y) editor = F1_left.text font = tkinter.font.Font(font=editor['font']) editor.config(tabs=font.measure(' ')) editor.see(INSERT) code_input = Text(master=F2_left, font=Font, width=50, yscrollcommand=b.set, borderwidth=2) code_input.pack(fill=BOTH, padx=2) b.config(command=code_input.yview) c = Scrollbar(master=F2_right, orient='vertical') c.pack(side=RIGHT, fill=Y) code_output = Text(master=F2_right,
def getTextWidth(self): f,s,b = self.config['font'] font = tkinter.font.Font(family=f, size=s) w = font.measure(self.getText()) return w
def get_width(self, font, max_line): return font.measure(max_line)