1 回答
![?](http://img1.sycdn.imooc.com/5458463b0001358f02200220-100-100.jpg)
TA贡献1993条经验 获得超5个赞
如果您只想更改单击时按钮的颜色,则需要使用.config()该按钮小部件上的方法。
例如,如果一个按钮定义如下
aButton = tk.Button(root, text='change my color').pack()
然后要更改颜色(或几乎所有与该小部件相关的内容,如文本、命令或其他内容),请调用该方法
aButton.configure(bg='#f0f', fg='#fff') # change to your required colors, bg is background, fg is foreground.
也可以使用OR .config()(这2种方法的作用完全相同)
aButton.config(bg='#f0f', fg='#fff')
现在你如何知道按钮何时存在clicked或不存在。最简单直观的方法是定义它们functions并将bind它们连接(或)到按钮。现在你想如何做到这一点完全取决于用户的喜好。有些人喜欢为所有按钮创建单独的不同功能,有些人只喜欢创建一个。
不过,对于您的情况,由于除了更改颜色之外您不需要做任何其他事情,因此单一功能就足够了。 重要在下面的示例代码中,我使用了lambda函数,一种特殊类型的函数,不需要单独定义。然而,这绝不是必要的
为您提供工作示例
from tkinter import * # I don't recommend using global import. better use "import tkinter as tk"
root = Tk()
button1=Button(root,text="A1",width=8, command=lambda: button1.config(bg='#f00'))
button1.grid(row=0,column=0)
button2=Button(root,text="A2",width=8, command=lambda: button2.config(bg='#f00'))
button2.grid(row=0,column=1)
Label(root,text=" ",padx=20).grid(row=0,column=2)
button22=Button(root,text="A3",width=8, command=lambda: button22.config(bg='#f00'))
button22.grid(row=0,column=3,sticky='E')
button23=Button(root,text="A4",width=8, command=lambda: button23.config(bg='#f00'))
button23.grid(row=0,column=4,sticky='E')
root.mainloop()
使用函数
from tkinter import * # I don't recommend using global import. better use "import tkinter as tk"
def changeColor(btn):
# Use your own highlight background argument here instead of bg
btn.configure(bg='#f00')
root = Tk()
button1=Button(root,text="A1",width=8, command=lambda: changeColor(button1))
button1.grid(row=0,column=0)
button2=Button(root,text="A2",width=8, command=lambda: changeColor(button2))
button2.grid(row=0,column=1)
Label(root,text=" ",padx=20).grid(row=0,column=2)
button22=Button(root,text="A3",width=8, command=lambda: changeColor(button22))
button22.grid(row=0,column=3,sticky='E')
button23=Button(root,text="A4",width=8, command=lambda: changeColor(button23))
button23.grid(row=0,column=4,sticky='E')
root.mainloop()
添加回答
举报