from tkinter import *
def plus():
print('Hello')
root = Tk()
Btn = Button(root, text="Show", command=plus()).pack()
root.mainloop()
Asked
Active
Viewed 80 times
-3

martineau
- 119,623
- 25
- 170
- 301

lukyjuranek
- 27
- 5
-
1Note also that `Btn` is not storing what you think it is. If you want to store a reference to `Btn` don't pack it in the same instruction line as the `Button` constructor call. Just make `Btn.pack()` in the next line. – progmatico Jan 11 '18 at 21:46
-
2Possible duplicate of [Tkinter buttons help](https://stackoverflow.com/questions/4046118/tkinter-buttons-help) – Aran-Fey Jan 11 '18 at 21:47
-
1This is the reason: http://stackoverflow.com/q/5767228/7432 – Bryan Oakley Jan 11 '18 at 23:28
2 Answers
3
No need for lambda. Just remove the ()
in Btn = Button(root, text="Show", command=plus()).pack()
. This is causing you to call the function before actually pressing the button.
Your button command should look like this:
Btn = Button(root, text="Show", command=plus).pack()

Xantium
- 11,201
- 10
- 62
- 89
-
-
-
1@user8921550 - edit your answer please, and add the code you posted as comment before. – progmatico Jan 11 '18 at 21:56
-
impor.... root=Tk def click(): print(E.get()) E = Entry(root) E.pack() btn = Button(root, text="click", command=click) btn.pack() – lukyjuranek Jan 11 '18 at 23:33
-
@user8921550 `from tkinter import * root = Tk() def click(): print(E.get()) E = Entry(root) E.pack() btn = Button(root, text="click", command=click) btn.pack() ` Works perfectly for me. You just missed the () on Tk. – Xantium Jan 11 '18 at 23:38
-
@user8921550 Please check your code again. This is working fine for me. – Xantium Jan 12 '18 at 12:32
-
-
-
@user8921550 I think `root=Tk` was the problem. That should be `root=Tk()` – Xantium Jan 12 '18 at 13:25
-
@user8921550. you may also [want to accept](https://stackoverflow.com/help/someone-answers) but only do that if you are satisfied with it and it did actually help. – Xantium Jan 12 '18 at 20:46
2
You could use a lambda. Code:
from tkinter import *
def plus(): print('Hello')
root = Tk()
Btn = Button(root, text="Show", command=lambda:plus()).pack()
root.mainloop()
Per the requests of the Anti-Lambda league below me, here is a non-lambda version:
from tkinter import *
def plus(): print('Hello')
root = Tk()
Btn = Button(root, text="Show", command=plus).pack()
root.mainloop()

JimmyCarlos
- 1,934
- 1
- 10
- 24
-
1It doesn't have to be a lambda, not in this case, and not in many other cases. Usually you need a lambda to pass parameters into the callback. – progmatico Jan 11 '18 at 21:44
-
-
You're right, the lambda wasn't necessary. Alternate version added. – JimmyCarlos Jan 11 '18 at 21:47