0

I tried to change the label text by pressing the "+" button, but if I run the program it is already changed to "testok" instead of "test" at start. So my question is why?

from tkinter import *
root = Tk()
var = "test"
label = Label(root, text=var)
label.pack()
button_plus = Button(root, text="+", command=label.config(text=var + "ok"))
button_plus.pack()
button_minus = Button(root, text="-", command=root.destroy)
button_minus.pack()

root.mainloop()
j_4321
  • 14,026
  • 2
  • 31
  • 53
  • Please mention the programming language. You should tag it to this question. – ElectricRouge Dec 03 '18 at 15:28
  • Possible duplicate of [Why is Button parameter “command” executed when declared?](https://stackoverflow.com/questions/5767228/why-is-button-parameter-command-executed-when-declared) – Bryan Oakley Dec 04 '18 at 02:58

1 Answers1

0

The command of button_plus is assigned the result of label.config(text=var+"ok") which is None. You can use lambda to do what you want:

button_plus = Button(root, text="+", command=lambda: label.config(text=var + "ok"))
acw1668
  • 30,224
  • 4
  • 17
  • 30