解決Tkinter中button按鈕未按卻主動執(zhí)行command函數(shù)的問題
在使用Tkinter做界面時,遇到這樣一個問題:
程序剛運(yùn)行,尚未按下按鈕,但按鈕的響應(yīng)函數(shù)卻已經(jīng)運(yùn)行了
例如下面的程序:
from Tkinter import * class App: def __init__(self,master): frame = Frame(master) frame.pack() Button(frame,text='1', command = self.click_button(1)).grid(row=0,column=0) Button(frame,text='2', command = self.click_button(2)).grid(row=0,column=1) Button(frame,text='3', command = self.click_button(1)).grid(row=0,column=2) Button(frame,text='4', command = self.click_button(2)).grid(row=1,column=0) Button(frame,text='5', command = self.click_button(1)).grid(row=1,column=1) Button(frame,text='6', command = self.click_button(2)).grid(row=1,column=2) def click_button(self,n): print 'you clicked :',n root=Tk() app=App(root) root.mainloop()
程序剛一運(yùn)行,就出現(xiàn)下面情況:

六個按鈕都沒有按下,但是command函數(shù)卻已經(jīng)運(yùn)行了
后來通過網(wǎng)上查找,發(fā)現(xiàn)問題原因是command函數(shù)帶有參數(shù)造成的
tkinter要求由按鈕(或者其它的插件)觸發(fā)的控制器函數(shù)不能含有參數(shù)
若要給函數(shù)傳遞參數(shù),需要在函數(shù)前添加lambda。
原程序可改為:
from Tkinter import * class App: def __init__(self,master): frame = Frame(master) frame.pack() Button(frame,text='1', command = lambda: self.click_button(1)).grid(row=0,column=0) Button(frame,text='2', command = lambda: self.click_button(2)).grid(row=0,column=1) Button(frame,text='3', command = lambda: self.click_button(1)).grid(row=0,column=2) Button(frame,text='4', command = lambda: self.click_button(2)).grid(row=1,column=0) Button(frame,text='5', command = lambda: self.click_button(1)).grid(row=1,column=1) Button(frame,text='6', command = lambda: self.click_button(2)).grid(row=1,column=2) def click_button(self,n): print 'you clicked :',n root=Tk() app=App(root) root.mainloop()
補(bǔ)充:Tkinter Button按鈕組件調(diào)用一個傳入?yún)?shù)的函數(shù)
這里我們要使用python的lambda函數(shù),lambda是創(chuàng)建一個匿名函數(shù),冒號前是傳入?yún)?shù),后面是一個處理傳入?yún)?shù)的單行表達(dá)式。
調(diào)用lambda函數(shù)返回表達(dá)式的結(jié)果。
首先讓我們創(chuàng)建一個函數(shù)fun(x):
def fun(x):
print x
隨后讓我們創(chuàng)建一個Button:(這里省略了調(diào)用Tkinter的一系列代碼,只寫重要部分)
Button(root, text='Button', command=lambda :fun(x))
下面讓我們創(chuàng)建一個變量x=1:
x = 1
最后點(diǎn)擊這個Button,就會打印出 1了。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Jupyter Notebook/VSCode導(dǎo)出PDF中文不顯示的解決
這篇文章主要介紹了Jupyter Notebook/VSCode導(dǎo)出PDF中文不顯示的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
簡單介紹Python中的try和finally和with方法
這篇文章主要介紹了Python中的try和finally和with方法,是Python學(xué)習(xí)當(dāng)中的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
將python圖片轉(zhuǎn)為二進(jìn)制文本的實(shí)例
今天小編就為大家分享一篇將python圖片轉(zhuǎn)為二進(jìn)制文本的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
詳解有關(guān)PyCharm安裝庫失敗的問題的解決方法
這篇文章主要介紹了詳解有關(guān)PyCharm安裝庫失敗的問題的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
人工智能學(xué)習(xí)Pytorch數(shù)據(jù)集分割及動量示例詳解
這篇文章主要為大家介紹了人工智能學(xué)習(xí)Pytorch數(shù)據(jù)集分割及動量示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11

