Generate a list of all available monospaced fonts

840 Views Asked by At

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()
2

There are 2 best solutions below

0
wkl On BEST ANSWER

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()
1
Bryan Oakley On

You can create an instance of the font and then check to see if it's monospace with the metrics method:

for fonts in available_fonts:
    f = font.Font(family=fonts)
    if f.metrics("fixed"):
        lbFonts.insert(tk.END, fonts)

This is what I see on my OSX system:

screenshot