亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在運行時更改按鈕的顏色?

如何在運行時更改按鈕的顏色?

皈依舞 2023-10-11 20:07:07
button1=Button(root,text="A1",width=8).grid(row=0,column=0)button2=Button(root,text="A2",width=8).grid(row=0,column=1)label1=Label(root,text="       ",padx=20).grid(row=0,column=2)button22=Button(root,text="A3",width=8).grid(row=0,column=3,sticky='E')button23=Button(root,text="A4",width=8).grid(row=0,column=4,sticky='E')我正在嘗試為學校項目制作座位安排系統。我有一個問題:單擊按鈕后如何更改按鈕的顏色?單擊該按鈕后,我想更改已預訂和可用座位的顏色。
查看完整描述

1 回答

?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

如果您只想更改單擊時按鈕的顏色,則需要使用.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它們連接(或)到按鈕?,F在你想如何做到這一點完全取決于用戶的喜好。有些人喜歡為所有按鈕創建單獨的不同功能,有些人只喜歡創建一個。


不過,對于您的情況,由于除了更改顏色之外您不需要做任何其他事情,因此單一功能就足夠了。 重要在下面的示例代碼中,我使用了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()


查看完整回答
反對 回復 2023-10-11
  • 1 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號