python中def定義的函數(shù)加括號(hào)和不加括號(hào)的區(qū)別?
問題描述
程序如下:
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()
這個(gè)程序的效果是 有一個(gè)按鈕,按一下,就出現(xiàn)you hit me 再按一下就消失,如此循環(huán)為什么button寫成button = tk.Button(window,text = ’生成題目和答案’,font = ((’微軟雅黑’),12),command = run()),函數(shù)調(diào)用時(shí)加了括號(hào),再按按鈕,就一直是you hit me ,上面的lable里的內(nèi)容不再變化了?
問題解答
回答1:button = tk.Button(window,text = ’hit’,font = ((’微軟雅黑’),12),command = run)
這句,只是將run這個(gè)函數(shù)本身讓button保存下來,在button被點(diǎn)擊后會(huì)自動(dòng)調(diào)用(相當(dāng)于點(diǎn)擊后才運(yùn)行run())。如果改成
button = tk.Button(window,text = ’hit’,font = ((’微軟雅黑’),12),command = run())
解釋器會(huì)在看到這句的時(shí)候立即調(diào)用一次run(),然后把調(diào)用的返回值讓button保存下來,現(xiàn)在button被點(diǎn)擊后調(diào)用的就是這個(gè)返回值(這個(gè)例子下就是None)。
回答2:command有兩種方式調(diào)用:b = Button(... command = button)b = Button(... command = lambda: button(’hey’))
你想要用()調(diào)用的話可以用lambda寫:button = tk.Button(window,text = ’生成題目和答案’,font = ((’微軟雅黑’),12),command =lambda:run())
相關(guān)文章:
1. Python從URL中提取域名2. php傳對(duì)應(yīng)的id值為什么傳不了啊有木有大神會(huì)的看我下方截圖3. python - scrapy url去重4. python - Flask寫的注冊(cè)頁面,當(dāng)注冊(cè)時(shí),如果填寫數(shù)據(jù)庫里有的相同數(shù)據(jù),就報(bào)錯(cuò)5. 關(guān)于mysql聯(lián)合查詢一對(duì)多的顯示結(jié)果問題6. 實(shí)現(xiàn)bing搜索工具urlAPI提交7. 數(shù)據(jù)庫 - Mysql的存儲(chǔ)過程真的是個(gè)坑!求助下面的存儲(chǔ)過程哪里錯(cuò)啦,實(shí)在是找不到哪里的問題了。8. python - oslo_config9. MySQL主鍵沖突時(shí)的更新操作和替換操作在功能上有什么差別(如圖)10. 小白學(xué)python的問題 關(guān)于%d和%s的區(qū)別
