-3
from tkinter import *

def plus():
    print('Hello')

root = Tk()

Btn = Button(root, text="Show", command=plus()).pack()

root.mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Note 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
  • 2
    Possible duplicate of [Tkinter buttons help](https://stackoverflow.com/questions/4046118/tkinter-buttons-help) – Aran-Fey Jan 11 '18 at 21:47
  • 1
    This is the reason: http://stackoverflow.com/q/5767228/7432 – Bryan Oakley Jan 11 '18 at 23:28

2 Answers2

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
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