python中def定義的函數加括號和不加括號的區別?
問題描述
程序如下:
import tkinter as tkwindow = tk.Tk()window.title('我的程序')window.geometry(’400x300’)var = tk.StringVar()lable = tk.Label(window,textvariable = var,font = ((’微軟雅黑’),12))lable.pack()on_hit = Truedef run(): global on_hit if on_hit == True:on_hit = Falsevar.set(’you hit me’) else:on_hit = Truevar.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里的內容不再變化了?
問題解答
回答1: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)。
回答2:command有兩種方式調用:b = Button(... command = button)b = Button(... command = lambda: button(’hey’))
你想要用()調用的話可以用lambda寫:button = tk.Button(window,text = ’生成題目和答案’,font = ((’微軟雅黑’),12),command =lambda:run())
相關文章:
1. golang - 用IDE看docker源碼時的小問題2. javascript - 請指條明路,angular的$event,在select中卻是undefined?3. 前端 - @media query 使用出現的問題?4. 我何時應該在Java中使用JFrame.add(component)和JFrame.getContentPane()。add(component)5. html - css氣泡,實現“倒三角(不知道算不算三角了)”可透明的。6. 運行python程序時出現“應用程序發生異常”的內存錯誤?7. docker - 如何修改運行中容器的配置8. 利用IPMI遠程安裝centos報錯!9. phpstudy8.1沒集成mysql-front10. html5和Flash對抗是什么情況?

網公網安備