Home > Net >  tk.Text: Tag Font
tk.Text: Tag Font

Time:07-17

Is there a way to get a proper Font instance out of a tag, so I can change just the size? I know I can dump it in tk.font.Font but that seems really inefficient ~ making hundreds of arbitrary font instances just to change a size.

for tag in self.tag_names():
    #I need `f` to be a Font instance, not just a string
    f = self.tag_cget(tag, 'font')

CodePudding user response:

If you used font objects to create the tags, then you can get the font name from the tag and then use nametofont to convert it to an instance of tkinter.font.Font. However, this only works if the tag has a font associated with it, and if the font is a font object rather than shorthand notation (eg: ("Helvetica", 24, "bold")).

from tkinter.font import nametofont
...
for tag_name in self.tag_names():
    font_name = self.tag_cget(tag_name, "font")
    if font_name:
        font = nametofont(font_name)
        size = int(font.cget("size"))
        font.configure(size = size   delta)

CodePudding user response:

You need to premake all of the Font instances and assign the instances to the applicable tag's font option. When you want to change the sizes, loop over the stored Font instances, and change their sizes directly. Every tag that uses your Font instances will change accordingly.

  • Related