Get list of all available fonts in Tkinter

In this tutorial, we explore Tkinter, the standard GUI library for Python, which provides a variety of properties to customize widgets, making it a powerful tool for creating desktop applications.

Among various properties of Tkinter, the font property stands out as particularly valuable, allowing developers to tailor the appearance of text in their applications. Despite its importance, determining which fonts are available in the Tkinter library can be a challenge. To address this, we can create an application that lists all the fonts available in Tkinter.

To leverage the font library in Tkinter, you first need to import it into your environment using:

from tkinter import font

Steps to Get list of all fonts:

  • Initialize a new Tkinter window using ‘tk.Tk()’. This window will serve as the main application window.
  • Use the ‘font.families()’ function to get a list of all available font families in ‘Tkinter’. Convert this list to a Python list for easier manipulation.
  • Create a Listbox widget to display the fonts. Specify the Listbox width and height to accommodate the font names.
  • Iterate over the fonts list and insert each font name into the Listbox using the ‘insert()’ method. This method adds each font name to the end of the Listbox.
  • Use the ‘pack’ method to add the Listbox to the Tkinter window. Add padding around the Listbox for a better appearance.

Code:

import tkinter as tk 
from tkinter import Tk,font
newWindow = tk.Tk()
all_fonts = list(font.families())
listbox = tk.Listbox(newWindow, width=100, height=30)
for font in all_fonts:
    listbox.insert(tk.END, font)
    listbox.pack(padx=20, pady=20)
newWindow.mainloop()

This code initializes a Tkinter window, retrieves a list of all available fonts, and displays them in a Listbox widget. By following these steps, you can easily explore and utilize the fonts provided by Tkinter in your applications.

Output:

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top