在使用Tkinter做界面時(shí),遇到這樣一個(gè)問(wèn)題:
程序剛運(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)下面情況:

六個(gè)按鈕都沒(méi)有按下,但是command函數(shù)卻已經(jīng)運(yùn)行了
后來(lái)通過(guò)網(wǎng)上查找,發(fā)現(xiàn)問(wè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)用一個(gè)傳入?yún)?shù)的函數(shù)
這里我們要使用python的lambda函數(shù),lambda是創(chuàng)建一個(gè)匿名函數(shù),冒號(hào)前是傳入?yún)?shù),后面是一個(gè)處理傳入?yún)?shù)的單行表達(dá)式。
調(diào)用lambda函數(shù)返回表達(dá)式的結(jié)果。
首先讓我們創(chuàng)建一個(gè)函數(shù)fun(x):
隨后讓我們創(chuàng)建一個(gè)Button:(這里省略了調(diào)用Tkinter的一系列代碼,只寫(xiě)重要部分)
Button(root, text='Button', command=lambda :fun(x))
下面讓我們創(chuàng)建一個(gè)變量x=1:
最后點(diǎn)擊這個(gè)Button,就會(huì)打印出 1了。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 關(guān)于Python Tkinter Button控件command傳參問(wèn)題的解決方式
- Python的Tkinter點(diǎn)擊按鈕觸發(fā)事件的例子
- Python 窗體(tkinter)按鈕 位置實(shí)例