网络编程
位置:首页>> 网络编程>> Python编程>> python 批量添加的button 使用同一点击事件的方法

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

作者:Cod_erL  发布时间:2022-10-11 20:13:46 

标签:python,批量,添加,button

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

来源:https://blog.csdn.net/u014510302/article/details/52535371

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com