[英]How can I change color of button when it pushed with tkinter?
I made 100 buttons and I want to change color of button which pushed.我做了 100 个按钮,我想改变按下按钮的颜色。 How can I do that?
我怎样才能做到这一点? Here is my code.
这是我的代码。
import tkinter as tk
def settingships():
column = -1
row = 0
root = tk.Tk()
root.title('set ships')
root.geometry('470x310')
for i in range(101):
if i > 0:
if i%10 == 1:
row += 1
column = -1
column += 1
text=f'{i}'
btn = tk.Button(root,text=text,command=collback(i)).grid(column=column,row=row)
root.mainloop()
def collback(i):
def nothing():
btn.config(bg='#008000')
return nothing
First, i
is not used in collback()
.首先,
i
不在collback()
中使用。 Second btn
is undefined in nothing()
.第二个
btn
在nothing()
中未定义。 You should pass btn
to collback()
instead.您应该将
btn
传递给collback()
。
In order to do that you need to replace the following line:为此,您需要替换以下行:
btn = tk.Button(root,text=text,command=collback(i)).grid(column=column,row=row)
to:至:
btn = tk.Button(root, text=text)
btn.grid(column=column, row=row)
btn.config(command=collback(btn))
And modify collback()
as below:并修改
collback()
如下:
def collback(btn):
def nothing():
btn.config(bg='#008000')
return nothing
Or simply use lambda to replace collback()
:或者简单地使用 lambda 替换
collback()
:
btn.config(command=lambda b=btn: b.config(bg='#008000'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.