What is the difference between functions defined by def in Python with parentheses and without parentheses?
我想大声告诉你
我想大声告诉你 2017-06-12 09:27:41
0
2
930

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

我想大声告诉你
我想大声告诉你

reply all(2)
phpcn_u1582
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 ).

Peter_Zhu

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!