-1

I am trying to create a button that changes a labels text, I feel like it should work fine, but the function that I assigned to the buttons command gets called before I even press the button, why is this happening and is there anything I can do to fix it?

Here is my code:

import tkinter as tk

def changeLabelText(my_label, new_text):
    my_label.config(text = new_text)

root = tk.Tk()
root.geometry("500x500")

label = tk.Label(root, text = "Old Text", font = ("font", 30))
label.grid(row = 0)

changeTextButton = tk.Button(root, text = "Click to change label text",
                             command = changeLabelText(label, "New Text"))
changeTextButton.grid(row = 1)

tk.mainloop()
Pythonieer
  • 17
  • 3

3 Answers3

1

Use lambda to pass variables to a call back.

command = lambda: changeLabelText(label, "New Text"))
ShayneLoyd
  • 633
  • 1
  • 4
  • 9
0

Instead of passing your function, you are calling it and passing what it returns. You can pass functions without parameters by just leaving out the brackets

command = func

or you can use lambdas:

command = lambda: changeLabelText(label, "New Text")
Lcj
  • 371
  • 3
  • 10
0

You should use the lambda for callback. It allows to create small, inline functions for the command parameter. The lambda function is an anonymous function in Python. You can read more about it: https://www.w3schools.com/python/python_lambda.asp

It means you should change this parameter command = changeLabelText(label, "New Text") to this command=lambda: changeLabelText(label, "New Text").

Complete code:

import tkinter as tk


def changeLabelText(my_label, new_text):
    my_label.config(text=new_text)


root = tk.Tk()
root.geometry("500x500")

label = tk.Label(root, text="Old Text", font=("font", 30))
label.grid(row=0)

changeTextButton = tk.Button(
    root, text="Click to change label text", command=lambda: changeLabelText(label, "New Text")
)
changeTextButton.grid(row=1)

tk.mainloop()

"Before click" GUI:

Before

"After click" GUI:

After

milanbalazs
  • 4,811
  • 4
  • 23
  • 45