在 python tkinter 中,我有一个程序可以生成多个默认fg
为红色的按钮
from tkinter import *
root = Tk()
def dothis(i):
print(i)
button.config(fg='green')
for i in range(5):
button = Button(root, width=30, text="button{}".format(i), command=lambda i=i: dothis(i))
button.config(fg='red')
button.pack()
这将创建此窗口:
在这个程序中,我试图让按下按钮后,文本 ( fg
)的颜色变为绿色。相反,当dothis(i)
被调用时,它会将生成的最后一个按钮的颜色更改为绿色。这不是我想要的。总而言之,当我点击 button3 时,我想看到这个:
但是相反,我看到了这个(最后生成的按钮被修改,不是我想要的):
我怎样才能解决这个问题,同时仍然保持在循环中生成的按钮?注意:更改颜色后,按钮也必须是可修改的,例如,一旦更改为绿色,就可以变回红色。
您得到了正确的lambda
表达式,但您传递的参数与您创建的按钮无关。您应该将Button
小部件作为参数传递:
from tkinter import *
root = Tk()
def dothis(button):
button.config(fg='green')
for i in range(5):
button = Button(root, width=30, text="button{}".format(i))
button.config(fg='red', command=lambda i=button: dothis(i))
button.pack()
root.mainloop()
要实现红色和绿色之间的切换,您可以使用三元运算符:
def dothis(button):
button.config(fg='green' if button["foreground"]=="red" else "red")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句