Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to change default font in Tkinter?

How to change default font in Tkinter?

Prerequisites: Tkinter

Tkinter provides a variety of fonts for different things i.e Heading, Caption, Text, Menu, etc. But the good thing is we can override these fonts using tkinter.font module.

Some fonts provided by the Tkinter are:

  • TkDefaultFont
  • TkMenuFont
  • TkFixedFont
  • TkSmallCaptionFont and so on.

In this article, we are going to change the default font. In order to do this, we need to override/ change the configuration of TkDefaultFont. Changing/ overriding the default font is very easy and can be done in the listed way:

  • Create the font object using font.nametofont method.
  • Use the configure method on the font object
  • Then change font style such as font-family, font-size, and so on.

Given below is the proper approach for doing the same.

Approach

  • Import module
  • Create window
  • Create the font object using font.nametofont method.
  • Use the configure method on the font object
  • Then change font style such as font-family, font-size, and so on.
  • Add required elements
  • Execute code

Program:

Python3




# Import tkinter.Tk and widgets
from tkinter import Tk, font
from tkinter.ttk import Button, Label
  
  
class App:
    def __init__(self, master: Tk) -> None:
        self.master = master
  
        # Creating a Font object of "TkDefaultFont"
        self.defaultFont = font.nametofont("TkDefaultFont")
  
        # Overriding default-font with custom settings
        # i.e changing font-family, size and weight
        self.defaultFont.configure(family="Segoe Script",
                                   size=19,
                                   weight=font.BOLD)
  
        # Label widget
        self.label = Label(self.master, text="I'm Label")
        self.label.pack()
  
        # Button widget
        self.btn = Button(self.master, text="I'm Button")
        self.btn.pack()
  
  
if __name__ == "__main__":
    # Top level widget
    root = Tk()
  
    # Setting window dimensions
    root.geometry("300x150")
  
    # Setting app title
    root.title("Changing Default Font")
  
    print(font.names())
  
    app = App(root)
  
    # Mainloop to run application
    # infinitely
    root.mainloop()


Output:

Before changing configuration

After changing configuration

RELATED ARTICLES

Most Popular

Recent Comments