search

Home  >  Q&A  >  body text

What is the difference between functions defined by def in Python with parentheses and without parentheses?

The procedure is as follows:

import tkinter as tk
window = tk.Tk()
window.title("我的程序")
window.geometry('400x300')
var = tk.StringVar()
lable = tk.Label(window,textvariable = var,font = (('微软雅黑'),12))
lable.pack()
on_hit = True
def run():
    global on_hit
    if on_hit == True:
        on_hit = False
        var.set('you hit me')
    else:
        on_hit = True
        var.set('')
button = tk.Button(window,text = 'hit',font = (('微软雅黑'),12),command = run)
button.pack()
window.mainloop()

The effect of this program is that there is a button. When you press it, you hit me will appear. Press it again and it will disappear. This cycle
Why is the button written as button = tk.Button(window, text = 'Generate questions and answers' , font = (('Microsoft Yahei'),12), command = run()), add parentheses when calling the function, press the button again, it will always be you hit me, and the content in the label above will no longer change. ?

我想大声告诉你我想大声告诉你2800 days ago1063

reply all(2)I'll reply

  • phpcn_u1582

    phpcn_u15822017-06-12 09:29:41

    button = tk.Button(window,text = 'hit',font = (('微软雅黑'),12),command = run)

    In this sentence, just save the button by the run function itself and it will be automatically called after the button is clicked (equivalent to running run() after clicking). If changed to

    button = tk.Button(window,text = 'hit',font = (('微软雅黑'),12),command = run())

    The interpreter will immediately call

    run() when it sees this sentence, and then save the return value of the call to the button. Now the return value is called after the button is clicked (in this example it is None ).

    reply
    0
  • 天蓬老师

    天蓬老师2017-06-12 09:29:41

    command can be called in two ways:
    b = Button(... command = button)
    b = Button(... command = lambda: button('hey'))

    If you want to use () to call, you can use lambda to write:
    button = tk.Button(window, text = 'Generate questions and answers', font = (('Microsoft Yahei'),12), command =lambda: run())

    reply
    0
  • Cancelreply