简体   繁体   中英

I want to change the background color of the button when I click in tkinter GUI

I have a python GUI code to open and close. I need to modify the code like when I press the open button the button colour turns into green and when I press close button the open button colour changes to its default colour.

from serial import*
from time import*
from tkinter import*

window = Tk()

def open_command():
    print("Opening")

def close_command():
    print("Closing")

b = Button(window, text = "Open", font = ("Times New Roman", 12), fg = "green", bg = "white", height = 1, width = 5, command = open_command).pack()
b = Button(window, text = "Close", font = ("Times New Roman", 12), fg = "red", bg = "white", height = 1, width = 5, command = close_command).pack()

mainloop()

when clicking open button colour of open button needs to change from its default colour to green. If we click close button close button colour needs to change red and open button colour changes to its default colour.

You can simply use .config(bg=...) to change the background color of the button to whatever color you want as below:

import tkinter as tk

window = tk.Tk()

def open_command():
    open_btn.config(bg='green')
    close_btn.config(bg='white')

def close_command():
    open_btn.config(bg='white')
    close_btn.config(bg='red')

font=('Times New Roman', 12)
open_btn = tk.Button(window, text='Open', font=font, fg='green', bg='white', width=5, command=open_command)
open_btn.pack()
close_btn = tk.Button(window, text='Close', font=font, fg='red', bg='white', width=5, command=close_command)
close_btn.pack()

window.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM