Changing the editor's font

As we saw from our blackjack game, fonts in Tkinter are usually handled by a font argument against a widget. The Text widget is no exception, this takes the same argument in the same format—a tuple of (family, size, styles).

To change the font in our text editor, we could decide ourselves what font the editor should be in and hard-code that into the declaration of our TextArea instance. However, we cannot guarantee that the user has that font installed, nor can we assume that they like writing in that font! We also cannot assume what font size the user can read best. The only solution is to allow the user to choose their own font settings and find a way of saving their chosen configuration for the next time they open our application.

Since .yaml files are working out so well, we shall just use these for persistent storage.

Other options for persistent storage include plain text files, pickle, shelve or SQLite (which will be covered in a later chapter of this book). 

To keep the interface of our text editor clean, we will use a second Toplevel window to display the font choosing screen. Go ahead and create a file named fontchooser.py in the same folder as the rest of your Python code:

import tkinter as tk
import tkinter.ttk as ttk
from tkinter.font import families

For this class we will be using a new module called font. This is a module that handles some font-related logic. In particular we only need one function from it—families. This function returns all available font families on the user's system. We can use this to build a list of available fonts for the user to choose from, and we know that they will definitely be installed.

As mentioned, this class will inherit from the Toplevel class, much like our FindWindow:

class FontChooser(tk.Toplevel):
def __init__(self, master, **kwargs):
super().__init__(**kwargs)
self.master = master

self.transient(self.master)
self.geometry('500x250')
self.title('Choose font and size')

Most of this code should look familiar. We initialize the Toplevel superclass with all of our keyword arguments, set a reference to the master widget, assign this window as a transient of its master, adjust its default size, and give the window a title of "Choose font and size".

We now need to find a way of displaying all of the available fonts to the user. We haven't really met a widget that will do this in a particularly friendly way yet, but one does exist—the Listbox widget.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset