python中def定義的函數(shù)加括號(hào)和不加括號(hào)的區(qū)別?
問(wèn)題描述
程序如下:
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寫(xiě)成button = tk.Button(window,text = ’生成題目和答案’,font = ((’微軟雅黑’),12),command = run()),函數(shù)調(diào)用時(shí)加了括號(hào),再按按鈕,就一直是you hit me ,上面的lable里的內(nèi)容不再變化了?
問(wèn)題解答
回答1:button = tk.Button(window,text = ’hit’,font = ((’微軟雅黑’),12),command = run)
這句,只是將run這個(gè)函數(shù)本身讓button保存下來(lái),在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保存下來(lái),現(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寫(xiě):button = tk.Button(window,text = ’生成題目和答案’,font = ((’微軟雅黑’),12),command =lambda:run())
相關(guān)文章:
1. css3 - progress漸變效果css2. css - label文字居中3. 為什么學(xué)習(xí)PHP4. javascript - vue項(xiàng)目里的package.json5. javascript - js輸入框限定字?jǐn)?shù)問(wèn)題6. pdo - mysql 簡(jiǎn)單注入疑問(wèn)7. javascript - table固定尾行,有人寫(xiě)過(guò)嗎?8. python - 關(guān)于爬取網(wǎng)站,下載圖片的時(shí)候碰到網(wǎng)址結(jié)構(gòu)問(wèn)題卡住9. android - 微信登陸不回調(diào)問(wèn)題10. python - matplotlib安裝之后使用出錯(cuò)
