1

I'm really sorry about the title being so unclear. Here is my issue. Say I have a code like this:

from tkinter import *

root = Tk()

def callback(str):
    print(str)
    root.destroy()

btn = Button(root,text='destroy',command=callback('Hello world!'))

btn.pack()

root.mainloop()

However, when I executed this an error popped out:

Traceback (most recent call last):
  File "/Users/abc/Documents/test/test.py", line 8, in <module>
    btn = Button(root,text='destroy',command=callback('Hello world!'))
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2647, in __init__
    Widget.__init__(self, master, 'button', cnf, kw)
  File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 2569, in __init__
    self.tk.call(
_tkinter.TclError: can't invoke "button" command: application has been destroyed

I figured out that I can't write command=callback() with the parentheses, instead I should write command=callback in order to make the program function correctly. However, it seemed that it only worked when no argument is required. If I need to pass an argument, the argument(s) should be in a pair of parentheses [e.g."callback('hello world!')"]. How can I pass an argument without writing a pair of parentheses? Thanks.

acw1668
  • 40,144
  • 5
  • 22
  • 34
Ziran Xu
  • 11
  • 1

1 Answers1

2

as TheLizzard has pointed out, change command = callback('Hello world!') into command = lambda: callback('Hello world!'), since just putting without lambda calls the function, but if you put it in a lambda it becomes like a mini function since lambdas are callable, the argument for command if I remember correctly, The given argument should callable, like a function for example

CunningBard
  • 144
  • 11