Reader small image

You're reading from  Python GUI Programming with Tkinter, 2nd edition - Second Edition

Product typeBook
Published inOct 2021
Reading LevelBeginner
PublisherPackt
ISBN-139781801815925
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Alan D. Moore
Alan D. Moore
author image
Alan D. Moore

Alan D. Moore is a data analyst and software developer who has been solving problems with Python since 2006. He's developed both open source and private code using frameworks like Django, Flask, Qt, and of course Tkinter, and is known to contribute to various open-source Python and JavaScript projects. Alan maintains a YouTube channel, “Alan D Moore Codes”, where he posts Python, PyQt, and Tkinter tutorials. Alan lives in Franklin, Tennessee, where he works for the County Government, and with his wife Cara raises a crew of children who are just as geeky as their dad.
Read more about Alan D. Moore

Right arrow

Reducing User Error with Validation and Automation

Things are going well for our project: the data entry form works well, the code is better organized, and the users are excited at the prospect of using the application. We're not ready for production yet, though! Our form doesn't yet perform the promised task of preventing or discouraging user errors: number boxes still allow letters, combo boxes aren't limited to the choices given, and dates are just text fields that have to be filled in by hand. In this chapter, we're going to set things right as we work through the following topics:

  • In Validating user input, we'll talk about some strategies for enforcing correct values in our widgets and how to implement them in Tkinter.
  • In Creating validated widget classes, we'll super-charge Tkinter's widget classes with some custom validation logic.
  • In Implementing validated widgets in our GUI, we'll use our new widgets to improve...

Validating user input

At first glance, Tkinter's selection of input widgets seems a little disappointing.

It gives us neither a true number entry that only allows digits, nor a truly keyboard-friendly, modern drop-down selector. We have no date inputs, email inputs, or other specially formatted input widgets.

Nevertheless, these weaknesses can become strengths. Because these widgets assume nothing, we can make them behave in a way that's appropriate to our specific needs. For example, alphabetical characters may seem inappropriate in a number entry, but are they? In Python, strings such as NaN and Infinity are valid float values; having a box that could increment numerals but also handle those string values may be very useful in some applications.

Of course, before we can tailor our widgets to our needs, we'll need to think about what exactly we want them to do. Let's do some analysis.

Strategies to prevent data errors

There is no universal...

Creating validated widget classes

As you can see, adding even very simple validation to Tkinter widgets involves several steps with some less-than-intuitive logic. Adding validation to even a fraction of our widgets could get quite verbose and ugly. However, we learned in the previous chapter that we can improve on Tkinter widgets by subclassing them to add new configuration and functionality. Let's see if we can apply this technique to widget validation by creating validated versions of Tkinter's widget classes.

For example, let's implement our five-character entry again, this time as a subclass of ttk.Entry, like so:

# five_char_entry_class.py
class FiveCharEntry(ttk.Entry):
  """An Entry that truncates to five characters on exit."""
  def __init__(self, parent, *args, **kwargs):
    super().__init__(parent, *args, **kwargs)
    self.error = tk.StringVar()
    self.configure(
      validate='all',
      validatecommand...

Implementing validated widgets in our GUI

Now that you know how to validate your widgets, you have your work cut out for you! We have 17 input widgets, and you'll have to write validation code like that shown in the previous section for all of them to get the behavior we need. Along the way, you'll need to make sure the widgets respond consistently to errors and present a consistent API to the application.

If that sounds like something you'd like to put off indefinitely, I can't blame you. Maybe there's a way we can cut down the amount of repetitive code we need to write.

Introducing the power of multiple inheritance

So far, we have learned that Python allows us to create new classes by subclassing, inheriting features from the superclass, and only adding or changing what's different about our new class. Python also supports building classes using multiple inheritance, in which a subclass can inherit from multiple superclasses. We can exploit...

Automating input

Preventing users from entering bad data is one way to improve the quality of their output; another approach is to automate the entry of data wherever the values are predictable. Using our understanding of how the forms are likely to be filled out, we can insert values that are very likely to be correct for certain fields.

Remember from Chapter 2, Designing GUI Applications, that the forms are nearly always recorded the same day that they're filled out, starting with Plot 1 and going to Plot 20 in order for each paper form.

Also remember that the Date, Time, Lab, and Technician values remain the same for each form that is filled in. That gives us the possibility of implementing some helpful automation, specifically:

  • The current date can automatically be inserted in the Date field
  • If the previous Plot was not the last plot in the lab, we can increment its value and leave the Time, Technician, and Lab values the same

Let's...

Summary

The application has really come a long way. In this chapter, we learned about Tkinter validation, created a validation mixin class, and used it to create validated versions of the Entry, Combobox, and Spinbox widgets. We also learned how to validate widgets like Radiobutton, which don't support the built-in validation framework. We validated different kinds of data on keystrokes and focus events, and created fields that dynamically change state or update their constraints based on the values of related fields. Finally, we automated input on several fields to reduce the amount of manual data entry required by the user.

In the next chapter, we're going to prepare our code base for expansion by learning how to organize a large application for easier maintenance. More specifically, we'll learn about the MVC pattern and how to structure our code in multiple files for simpler maintenance. We'll also learn about version control software and how it can help...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Python GUI Programming with Tkinter, 2nd edition - Second Edition
Published in: Oct 2021Publisher: PacktISBN-13: 9781801815925
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Alan D. Moore

Alan D. Moore is a data analyst and software developer who has been solving problems with Python since 2006. He's developed both open source and private code using frameworks like Django, Flask, Qt, and of course Tkinter, and is known to contribute to various open-source Python and JavaScript projects. Alan maintains a YouTube channel, “Alan D Moore Codes”, where he posts Python, PyQt, and Tkinter tutorials. Alan lives in Franklin, Tennessee, where he works for the County Government, and with his wife Cara raises a crew of children who are just as geeky as their dad.
Read more about Alan D. Moore