Search code examples
pythontkintertk-toolkittkinter-entry

Python Tkinter - Multiple entry box with same validation


I have created around 5 Entry boxes and binded them as well. Take this as model:

def makeEntry(self, master, data):
    self.entry = Entry(master, width=8, textvariable=data)
    self.entry.bind("<Leave>", lambda event, value=data: self.validate(event, value))

Now, I did also a validate method that check if the input was a string (and if so, the highlight background of the entry would change to red). The problem which is still taking me a lot of time is that I would need that the method should be able to check every entries, and if at least one of them has got a red background, then a final button should be disabled (button.configure(state=DISABLED)).

With just one entry it would be much easier, I would simply check if the background was red (status = str(self.myOneEntry.cget("highlightbackground"))), but what about with more entries?


Solution

  • If you want to check all of your entries, keep them in a list. Then, write a function that iterates over the list and sets the button state to disabled if any widget has a red background. You can then call this whenever something changes, such as within your validation function for each widget.

    Example:

    class Example(...):
        def __init__(...):
            self.entries = []
            for data in ("one","two","three"):
                entry = makeEntry(...)
                self.entries.append(entry)
    
        def _update_button(self):
            for entry in self.entries:
                if entry.cget("background") == "red":
                    self.button.configure(state="disabled")
                    return
            self.button.configure(state="normal")
    

    Note: you'll need to make sure that makeEntry(...) returns a reference to the created widget.

    Also, you don't have to use makeEntry. You can create your widgets however you want. The point is to save references to the widgets in a data structure that you can iterate over. It doesn't matter how the widgets are created.