0

When I created this module I first made the tkinter window (all of its settings globally) it worked as intended. I could run the module and the window worked, taking the input from the entry field and displaying the welcome or error message. But when I put them into a function, it stopped working correctly, as shown. How the window looks when created globally, with the button and input working:

https://gyazo.com/ffcb16416b8a971c09bfa60ee9367bbd

How it looks when created inside the function:

https://gyazo.com/c8858a2793befafa41e71d1099f021d3

The error message pops up straight away, then the main window with the entry field but not the button.

Here's the code where I created the window and settings inside a function:

def userSign(userEntry):
    userId = userEntry.get()
    if userId.isdigit() == True and len(userId) == 4:
        welcomeWindow = tkinter.Tk()
        welcomeWindow.title("Welcome")
        welcomeWindow.geometry("200x50")
        welcome = tkinter.Label(master=welcomeWindow, text="Welcome "+userId,font=("Helvetica", 18, "bold"))
        welcome.grid()
        welcomeWindow.mainloop()
    else:
        errorWindow = tkinter.Tk()
        errorWindow.title("ERROR")
        errorWindow.geometry("500x50")
        error = tkinter.Label(master=errorWindow, text="ERROR: "+userId +" DOES NOT MEET CRITERIA", font=("Helvetica", 18, "bold"))
        error.grid()
        userId=""
        errorWindow.mainloop()      

def show():
    window = tkinter.Tk()
    window.title("Sign In")
    window.geometry("250x100")

    signInPrompt = tkinter.Label(master = window, text = "Enter your ID to sign in")
    signInPrompt.grid(column=0,row=2)

    userEntry = tkinter.Entry(master = window)
    userEntry.grid(column=0,row=4)

    enterButton = tkinter.Button(master = window, text="Sign in", command=userSign(userEntry))
    enterButton.grid(column=0,row=6)

    window.mainloop()

How do I get it so that my window works correctly when created inside functions as this module needs to be called by a different, main module.

  • 1
    Possible duplicate of [Why is Button parameter “command” executed when declared?](https://stackoverflow.com/questions/5767228/why-is-button-parameter-command-executed-when-declared) – fhdrsdg Nov 22 '18 at 14:13

1 Answers1

0

You are creating two instances of Tk() which is a bad idea. Instead use Toplevel() for additional windows.

When you create variables or widgets inside a function the names are in the local scope and not available outside the function. And whan the function ends they will be garbage colletced.

Also, as @fhdrsdg points out, problems in the button command.

figbeam
  • 7,001
  • 2
  • 12
  • 18