What is wrong with these lines?

Question:

I have the following lines in a large program.

username = Entry(loginPage)
password = Entry(loginPage)

button1 = Button(loginPage,text = "Login", fg = "red", command = loginClicked(username.get(),password.get()))

When the program is run, the function loginClicked runs once at the start (when the fields are empty and the button hasn’t been clicked) and that is the only time it runs. After, when the button is clicked the function doesn’t run at all. A print statement in the function confirms this.

Asked By: RazDoog

||

Answers:

As mentioned in the comments, when you create the widget you are calling (‘running’) the function before the widget is created, instead of passing the function handle (may be wrong terminology here) to the widget option command=.

This can be solved by using anonymous functions with lambda:

button1 = Button(root,text = "Login",
                 fg = "red", 
                 command = lambda: loginClicked(username.get(), password.get()))

This creates a ‘throw-away’ function to feed into Tkinter’s callback, which calls your function loginClicked() with its correct arguments.

You can also read effbot.org for more information on Tkinter callbacks

Answered By: Jamie Phan