tkinter怎么for循环创建多个参数不同的Button
本帖最后由 lawrence1357 于 2021-2-4 21:27 编辑from tkinter import *
class For_button:
def __init__(self, root):
self.root = root
for xin range(10) :
locals()['bnt'+str(x)]=Button(self.root, text=x)
locals()['bnt'+str(x)].grid()
locals()['bnt'+str(x)].config(command = lambda: self.fun_with_args(x))
def fun_with_args(self,x):
num=x
print('------------2-------------')
print(num)
if __name__=='__main__':
root=Tk()
For_button(root)
mainloop()
这个参数x每一次都传的是9,不应该是第一个button传0,第二个传1吗 class For_button:
def __init__(self, root):
self.root = root
for x in range(10) :
locals()['bnt'+str(x)]=Button(self.root, text=x)
locals()['bnt'+str(x)].grid()
locals()['bnt'+str(x)].config(command = self.fun_with_args(x))
def fun_with_args(self,x):
def r():
num=x
print('------------2-------------')
print(num)
return r
from tkinter import *
class For_button:
def __init__(self, root):
self.root = root
for xin range(10) :
locals()['bnt'+str(x)]=Button(self.root, text=x)
locals()['bnt'+str(x)].grid()
locals()['bnt'+str(x)].config(command = lambda x=x: self.fun_with_args(x))
def fun_with_args(self,x):
num=x
print('------------2-------------')
print(num)
if __name__=='__main__':
root=Tk()
For_button(root)
mainloop()
from functools import partial
locals()['bnt'+str(x)].config(command = partial(self.fun_with_args,x))
还想起来个方法 kogawananari 发表于 2021-2-4 21:23
感谢 kogawananari 发表于 2021-2-4 21:23
我又遇到一个问题,发了一个求助帖,如果可以的话请您帮忙解答一下,谢谢
页:
[1]