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. 人工智能 - python 機器學習 醫療數據 怎么學2. python - oslo_config3. mysql優化 - mysql 一張表如果不能確保字段列長度一致,是不是就不需要用到char。4. python - 請問這兩個地方是為什么呢?5. Python處理Dict生成json6. 請教一個mysql去重取最新記錄7. javascript - 按鈕鏈接到另一個網址 怎么通過百度統計計算按鈕的點擊數量8. python2.7 - python 正則前瞻 后瞻 無法匹配到正確的內容9. 大家都用什么工具管理mysql數據庫?10. php - 有關sql語句反向LIKE的處理
