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

来源:互联网 发布:淘宝怎么快速上穿 编辑:程序博客网 时间:2024/05/22 09:39

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的集合。


帮同事做了个小工具 碰到的问题  git  https://github.com/liqingju123/local_search

QQ:973683374









0 0