I decided to build a GUI that would seemlessly create user interfaces for validation
functions, functions that check if a string satisfies given rules.
An example 'hello, world!' usage is:
from gui_validation import gui_validation
def is_valid_salutation(salutation):
"""
Salutations to be valid must start with one of:
['hello', 'hi', 'howdy'] + ',' [COMMA]
and must end with '!' [EXCLAMATION MARK]
>>> is_valid_salutation('howdy, moon!')
True
>>> is_valid_salutation('random phrase')
False
"""
return any(salutation.startswith(i+',') for i in ['hello', 'hi', 'howdy']) \
and salutation.endswith('!')
if __name__ == "__main__":
gui_validation(is_valid_salutation)
As you can see the only argument required is the function itself.
gui_validation.py
"""
General purpose user input validation GUI.
"""
import tkinter
from tkinter.constants import X
from tkinter import messagebox
def gui_validation(validator, title=None, text=None, button_text="Validate"):
"""
Provides a general purpose gui to validate user input.
The user will be prompted to enter a string and will be
given feedback by the `validator` function.
This interface avoids verbosity and assumes the title to be
the `validator` name and the text to be the `validator` doc if not +
told explicitly.
"""
if title is None:
title = validator.__name__.replace('_',' ').capitalize()
if text is None:
text = validator.__doc__
def validate():
if validator(user_input.get()):
messagebox.showinfo("Input valid.",
"Congratulations, you entered valid input.")
else:
messagebox.showerror("Input NOT valid.",
"Please try again and enter a valid input.")
root = tkinter.Tk()
root.wm_title(title)
title_label = tkinter.Label(root, text=title, font='25px')
title_label.pack(fill=X, expand=1)
text_label = tkinter.Label(root, text=text, font='20px')
text_label.pack(fill=X, expand=1)
user_input = tkinter.Entry(root)
user_input.pack()
button = tkinter.Button(root, text=button_text, command=validate)
button.pack()
root.mainloop()
I was wondering:
- Would a class make the code clearer or just more verbose?
- Am I asking too little, should I force the user to give more details?
- Is it OK to use big fonts? The small fonts are much less legible to me.
- Any other improvement?