How do I validate tkinter askstring entries?

572 views Asked by At

If a user clicks OK on a tkinter askstring box without entering anything I want a warning message box to pop up and then present the user with another askstring box. In the code below I try to do this with a recursive call. I am seeing the two following behaviors:

  1. User enters data in the text field of the first instance of askstring, clicks OK. The function returns the value that was entered.
  2. User leaves the textfield of the first instance of askstring empty, clicks OK, responds to the warning message box and does enter data in the second askstring instance. The function returns None.

What is going on here?

    import tkinter as tk
    from tkinter import simpledialog
    from tkinter import messagebox

    def entry():
        temp=simpledialog.askstring("","")
        if len(temp) == 0:
            messagebox.showwarning("Oh oh","you gotta enter something here")
            entry()
        else:
            return(temp)

    y = entry()
    print (y)


      
1

There are 1 answers

0
P Schmurr On

Thanks to acw1668, I changed my code to a while loop instead of recursion and am now getting the desired result. Here is my solution:

    import tkinter as tk
    from tkinter import simpledialog
    from tkinter import messagebox

        def entry():
            temp=simpledialog.askstring("","")
            while len(temp) == 0:
                messagebox.showwarning("Oh oh","you gotta 
                enter something here")
                temp = simpledialog.askstring("", "")
            else:
                   return temp
        y = entry()

        print (y)