首页 >社区问答列表 >python中def定义的函数加括号和不加括号的区别?

python中def定义的函数加括号和不加括号的区别?

程序如下:

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

这个程序的效果是 有一个按钮,按一下,就出现you hit me 再按一下就消失,如此循环
为什么button写成button = tk.Button(window,text = '生成题目和答案',font = (('微软雅黑'),12),command = run()),函数调用时加了括号,再按按钮,就一直是you hit me ,上面的lable里的内容不再变化了?

  • phpcn_u1582
  • phpcn_u1582    2017-06-12 09:29:412楼

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

    这句,只是将run这个函数本身让button保存下来,在button被点击后会自动调用(相当于点击后才运行run())。
    如果改成

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

    解释器会在看到这句的时候立即调用一次run(),然后把调用的返回值让button保存下来,现在button被点击后调用的就是这个返回值(这个例子下就是None)。

    +0添加回复

  • 回复
  • 天蓬老师
  • 天蓬老师    2017-06-12 09:29:411楼

    command有两种方式调用:
    b = Button(... command = button)
    b = Button(... command = lambda: button('hey'))

    你想要用()调用的话可以用lambda写:
    button = tk.Button(window,text = '生成题目和答案',font = (('微软雅黑'),12),command =lambda:run())

    +0添加回复

  • 回复