Dec-22-2022, 12:08 AM
(This post was last modified: Dec-22-2022, 12:08 AM by deanhystad.)
You can use a validation callback to limit what is typed in an entry.
Note that the validate function does not force the zip code to be 5 digits long. '123' is valid. To ensure that the zip code is 5 digits long you would still need some type of form validation very much like in menator's post.
In this example the validate function is a static method, but it can be a standalone function.
Read about validators here:
https://anzeljg.github.io/rin2/book2/240...ation.html
https://www.geeksforgeeks.org/python-tki...ry-widget/
import tkinter as tk from tkinter import messagebox class Window(tk.Tk): def __init__(self): super().__init__() label = tk.Label(self, text="Zip Code") reg = self.register(self.zip_validate) self.zip_code = tk.StringVar(self, '') entry = tk.Entry( self, textvariable=self.zip_code, width=7, justify=tk.RIGHT, validate='key', validatecommand=(reg, '%P')) button = tk.Button(self, text='Accept', command=self.submit) button.pack(side=tk.BOTTOM, padx=5, pady=5, expand=True, fill=tk.X) label.pack(side=tk.LEFT, padx=5, pady=5) entry.pack(side=tk.RIGHT, padx=5, pady=5) @staticmethod def zip_validate(zip_code): return zip_code.isdigit() and len(zip_code) <= 5 def submit(self): if len(self.zip_code.get()) < 5: messagebox.showerror('Error', 'Zip code must be 5 digits', parent=self) Window().mainloop()This example registers a validation callback function named 'zip_validate'. The function is called whenever a key is pressed ('key'). The function is passed a preview of what the entry contents will be if the key press is accepted ('%P'). The validator returns True if the new content is acceptable, else False.
Note that the validate function does not force the zip code to be 5 digits long. '123' is valid. To ensure that the zip code is 5 digits long you would still need some type of form validation very much like in menator's post.
In this example the validate function is a static method, but it can be a standalone function.
Read about validators here:
https://anzeljg.github.io/rin2/book2/240...ation.html
https://www.geeksforgeeks.org/python-tki...ry-widget/