您的位置:首页 > 编程语言 > Python开发

python 批量添加的button 使用同一点击事件的方法

2019-07-17 09:09 483 查看

python 批量添加的button 使用同一点击事件根据传递的参数进行区分。

def clear_text():

print '我只是个清空而已'
def clear_text(index):

print '我只是个清空而已' +str(index)
button = Button(framet_title, text='清空', command=clear_text)

这样去设置,单个按钮对应单个点击事件没有问题的

如果你是

for i in Range(10):

button = Button(framet_title, text='清空', command=clear_text_list(i))

这样搞的话 当你程序启动的时候 回调函数就会直接执行,点击按钮是没有任何反应的,使用 button.bind的方式几乎是一样的

这种写法 如果是在JAVA C HTML C++ 是没有任何问题的。请原谅 我是个做android开发 程序员。我最纳闷的是 我明明 是每个按钮都给他单独设置了 回调。为什么会提前回调,并且 点击的时候没有任何反应。

for i in Range(10):

button = Button(framet_title, text='清空', command=lambda:clear_text_list(i))

如果在 添加 lambda 程序启动是不会回调了。但是每次点击 获得的索引还是最后一个。

Google 了一圈 (说实话 我不知道用什么关键字。。。) http://stackoverflow.com/ 上面我尝试 python buttons command lambda

找到了 http://stackoverflow.com/questions/20596892/disabling-buttons-after-click-in-tkinter

正确的姿势是

for index in range(9):
n=letters[index]

button = Button(root, bg="White", text=n, width=5, height=1, relief=GROOVE,
command=lambda index=index, n=n: appear(index, n))

看到答案 之后 开始找答案对的理由吧 他是用lambda 表达式 做成了个 点击事件的集合 正好对应 button的集合。

以上这篇python 批量添加的button 使用同一点击事件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 批量 添加 button
相关文章推荐