1 回答

TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
如果您只想更改單擊時(shí)按鈕的顏色,則需要使用.config()該按鈕小部件上的方法。
例如,如果一個(gè)按鈕定義如下
aButton = tk.Button(root, text='change my color').pack()
然后要更改顏色(或幾乎所有與該小部件相關(guān)的內(nèi)容,如文本、命令或其他內(nèi)容),請(qǐng)調(diào)用該方法
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')
現(xiàn)在你如何知道按鈕何時(shí)存在clicked或不存在。最簡(jiǎn)單直觀的方法是定義它們functions并將bind它們連接(或)到按鈕?,F(xiàn)在你想如何做到這一點(diǎn)完全取決于用戶的喜好。有些人喜歡為所有按鈕創(chuàng)建單獨(dú)的不同功能,有些人只喜歡創(chuàng)建一個(gè)。
不過(guò),對(duì)于您的情況,由于除了更改顏色之外您不需要做任何其他事情,因此單一功能就足夠了。 重要在下面的示例代碼中,我使用了lambda函數(shù),一種特殊類(lèi)型的函數(shù),不需要單獨(dú)定義。然而,這絕不是必要的
為您提供工作示例
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()
使用函數(shù)
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()
添加回答
舉報(bào)