Search code examples
pythontkinterfontsmonospace

Generate a list of all available monospaced fonts


Currently, I am using working code to generate a list of available fonts. However, I'd like to only show the list of avaliable monospaced (TkFixedFont)

from tkinter import font


def changeFont(event):
   selection = lbFonts.curselection()
   laExample.config(font=(available_fonts[selection[0]], "16"))

root = tk.Tk()
available_fonts = font.families()

lbFonts = tk.Listbox(root)
lbFonts.grid()

for fonts in available_fonts:
   lbFonts.insert(tk.END, fonts)

lbFonts.bind("<Double-Button-1>", changeFont)

laExample = tk.Label(root,text="Click Font")
laExample.grid()



root.mainloop()

Solution

  • Each font has a metrics property that tells you if the family is monospaced (or fixed-width).

    This is a general piece of code that can generate all the available font families that are monospace on your machine.

    from tkinter import *
    from tkinter import font
    
    if __name__ == "__main__":
      root = Tk()
      fonts = [font.Font(family=f) for f in font.families()]
      monospace = (f for f in fonts if f.metrics("fixed"))
    
      lbfonts = Listbox(root)
      lbfonts.grid()
    
      for f in monospace:
        lbfonts.insert(END, f.actual('family'))
    
      root.mainloop()