Building a font selector

Now that we have seen the basic features that are available in Tkinter's font module, let's implement a font selector like the one shown in the following screenshot:

The key to building the font selector shown in the preceding screenshot is to fetch a list of all the fonts installed on a system. A call to the families() method from the font module fetches a tuple of all the fonts available on a system. Accordingly, when you run the following code, a tuple of all the fonts available on the system gets printed (see the 10.09_all_fonts_on_a_system.py code):

from tkinter import Tk, font
root = Tk()
all_fonts = font.families()
print(all_fonts) # this prints the tuple containing all fonts on a system.

Note that since font is a submodule of Tkinter, it needs an instance of Tk(), which loads the Tcl interpreter, before it can fetch the tuple.

Now that we have a tuple of all the fonts available on a system, we just need to create the GUI shown in the preceding screenshot and attach relevant callbacks to all the widgets.

We will not discuss the code that creates the GUI shown in the preceding screenshot. Check out 10.10_font_selector.py for the complete code. However, note that the code attaches the following callback to all the widgets:

def on_value_change(self, event=None):
self.current_font.config(family=self.family.get(), size=self.size.get(),
weight=self.weight.get(), slant=self.slant.get(),
underline=self.underline.get(),
overstrike=self.overstrike.get())
self.text.tag_config('fontspecs', font=self.current_font)

Here, fontspecs is a custom tag that we attached to the sample text in the text widget, as follows:

self.text.insert(INSERT, '{}
{}'.format(self.sample_text,  
self.sample_text.upper()), 'fontspecs')

This concludes our brief discussion on playing with fonts in Tkinter. 

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

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