The Listbox widget

The Listbox widget displays a large scrollable box with vertically-stacked options. Depending on the configuration, the user can select either one or multiple items from within the widget.

Methods that act on the Listbox widget may seem familiar from our work with the Text widget. These include insert, delete, and get.  The indexing system is simpler, however, being just an integer representing how many items down the list the indicated entry is (for example, the third entry in the box has index 3).

Let's create a Listbox widget to hold our choices of font family:

self.font_list = tk.Listbox(self, exportselection=False)

self.available_fonts = sorted(families())

for family in self.available_fonts:
self.font_list.insert(tk.END, family)

We create a Listbox widget and store a reference to it under an attribute named font_list. As always, the first argument to a widget is its parent, and we use the keyword argument exportselection=False to prevent the Listbox from losing its selected option when the widget loses focus.

The font families are sorted so they appear in alphabetical order, then we loop over them and use the insert method to add them into our Listbox. The END constant is used to ensure that each new item is pushed to the end of the listbox, keeping the alphabetical order.

We now need to select the currently chosen font in our Listbox so that the user can see what font they are currently writing in. This information will be available in the TextEditor class later, but we can refer to it by the font_family attribute in this class:

current_selection_index = self.available_fonts.index(self.master.font_family)
if current_selection_index:
self.font_list.select_set(current_selection_index)
self.font_list.see(current_selection_index)

To get the location of the currently set font, we just need to pass the font family (as a string) to the index method, which returns us an integer representing its index. Since our master will have a reference to the chosen font family, we can pass this to the index method to get its index.

If we have received an index, we can use the select_set method to automatically select the currently set font family in our Listbox. The see method can also be used to scroll the chosen family into view.

That's it for our Listbox widget. We now have an easy to use interface for the user to select a font family that is installed on their system.

We now need to allow them to set the font size. To do this we could use a simple Entry widget, but we would have to write validation to prevent them from submitting any letters, since the font size should only contain numbers.

Thankfully, Tkinter provides a number-only input widget called a Spinbox.

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

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