-2

Just starting out with tkinter and was checking on button and this problem arose.

import tkinter as tk


def showtext(text):
 txt = tk.Text(gui)
 txt.insert(tk.END, text)
 txt.pack()


 gui = tk.Tk()
 btn = tk.Button(gui, text="this is a button", fg="white", bg="black",
            activebackground="red", activeforeground="purple", command=showtext("this worked"))
 btn.place(x=280, y=230)


gui.title('GUI')
gui.geometry("700x500+50+50")
gui.mainloop()

Here the text is supposed to be shown when the button is clicked, but the function is executed before that and the text is shown when I run the code.

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • You should probably fix the indentation of your code so that it actually reproduces the problem you are describing. – khelwood May 23 '21 at 07:42
  • 2
    Does this answer your question? [Why is the command bound to a Button or event executed when declared?](https://stackoverflow.com/questions/5767228/why-is-the-command-bound-to-a-button-or-event-executed-when-declared) – Thingamabobs May 23 '21 at 09:55

2 Answers2

0
 btn = tk.Button(gui, text="this is a button", fg="white", bg="black",
            activebackground="red", activeforeground="purple", command=showtext("this worked"))

Doing so mean: do showtext("this worked") and use returned value as command, you probably mean function to be command not its' return value so you should do command=showtext.

Daweo
  • 31,313
  • 3
  • 12
  • 25
  • `command=showtext` does not work because callback for `command` option of a button requires no argument, but `showtext` requires one. – acw1668 May 23 '21 at 12:37
0

Try this:

import tkinter as tk


def showtext(text):
 txt = tk.Text(gui)
 txt.insert(tk.END, text)
 txt.pack()


gui = tk.Tk()
btn = tk.Button(gui, text="this is a button", fg="white", bg="black",
            activebackground="red", activeforeground="purple", command=lambda: showtext("this worked"))
btn.place(x=280, y=230)


gui.title('GUI')
gui.geometry("700x500+50+50")
gui.mainloop()

I have used a lambda in the command and fixed your indentation.

  • yeah it did worked but can you explain why using lambda worked but not when i passed the function directly – Anupam Khatiwada May 24 '21 at 02:32
  • "A Lambda function can have multiple arguments with one expression. " Your function needs arguments, and in Python, if you have a statement like ```command=function(arguments, arguments, arguments)```, Python directly interprets it. So, we use a lambda function so that it gets interpreted when it is called. –  May 24 '21 at 09:41