How to use google font in tkinter

Is There any way to use google custom fonts in Tkinter Application. I have google Font zip file from google font and I want to use that in my tkinter application.

1 answer

  • answered 2021-11-29 04:33 Aleksas

    I've came to the same problem, unfortunately it doesn't seem to be possible to use custom fonts in traditional way anyways.

    But I came to a workaround by making a image with that text onto it.

    def create_text_image(self, text, color_rgba_code_tuple):
            fnt = Enums.ImageFont.truetype(Enums.FONT_DEFAULT, Enums.FONT_SIZE)
            text_width, text_height = fnt.getsize(text)
    
            img = Enums.Image.new('RGBA', (text_width,text_height))
            d = Enums.ImageDraw.Draw(img)
            d.text((0,0), text, font=fnt,fill=color_rgba_code_tuple)
            img.save(Enums.FONT_TEMPORARY_IMAGE_PATH)
            return Enums.PhotoImage(file=Enums.FONT_TEMPORARY_IMAGE_PATH)
    

    Imports

    from PIL import Image, ImageDraw, ImageFont, ImageTk
    

    Explanation

    You need to pass in your text and rgba tuple into the function; so, something like (255,255,255,255) for white text.

    And then simply add that image that the function returns to a list, and use it in wherever place you want (like Canvas for example).

    Hope this is clear.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum