在使用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):
def fun(x): print x
随后让我们创建一个button:(这里省略了调用tkinter的一系列代码,只写重要部分)
button(root, text='button', command=lambda :fun(x))
下面让我们创建一个变量x=1:
x = 1
最后点击这个button,就会打印出 1了。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。
黄山市民网:https://www.huangshanshimin.com/