在使用Tkinter做界面時,遇到這樣一個問題:
程序剛運行,尚未按下按鈕,但按鈕的響應函數卻已經運行了
例如下面的程序:
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()
程序剛一運行,就出現下面情況:

六個按鈕都沒有按下,但是command函數卻已經運行了
后來通過網上查找,發現問題原因是command函數帶有參數造成的
tkinter要求由按鈕(或者其它的插件)觸發的控制器函數不能含有參數
若要給函數傳遞參數,需要在函數前添加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()
補充:Tkinter Button按鈕組件調用一個傳入參數的函數
這里我們要使用python的lambda函數,lambda是創建一個匿名函數,冒號前是傳入參數,后面是一個處理傳入參數的單行表達式。
調用lambda函數返回表達式的結果。
首先讓我們創建一個函數fun(x):
隨后讓我們創建一個Button:(這里省略了調用Tkinter的一系列代碼,只寫重要部分)
Button(root, text='Button', command=lambda :fun(x))
下面讓我們創建一個變量x=1:
最后點擊這個Button,就會打印出 1了。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 關于Python Tkinter Button控件command傳參問題的解決方式
- Python的Tkinter點擊按鈕觸發事件的例子
- Python 窗體(tkinter)按鈕 位置實例