Search code examples
pythontkinterbackground-colortkinter-entry

Change background colour of entry box when button clicked, (entry box with loop)


Here is my code:

from tkinter import *

root = Tk()

fields = 'Name', 'Age'
entries = []
UserInps = []

def Form(root, fields):
    for field in fields:
        row = Frame(root)
        vertical = Frame(root)
        lab = Label(row, text=field)
        ent = Entry(row)
        row.pack()
        vertical.pack()
        lab.pack()
        ent.pack()
        entries.append((field, ent))
    return entries

def Check():
    if (entries[0][1].get()) == "B": #checks if the name inputted is "B"
        #HERE IS THE CODE THAT I NEED. HOW DO I CHANGE THE BACKGROUND COLOUR OF THE ENTRY BOX FOR NAME TO GREEN

if __name__ == '__main__':
    ents = Form(root, fields)
    row = Frame(root)
    row.pack()

    CheckButton = Button(row, text="Check", command=Check)
    CheckButton.pack()

root.mainloop()

The code runs fine I just don't know how to change the colour of the background of the name entry box. So in this example, like it states if the user enters the name "B", I want that specific entry box (where they entered B) to change to blue.

And before anyone asks why I am using a loop when there is just a form with two rows. My actual project has more rows. This is just a dumbed down version to post on here.


Solution

  • if entries[0][1].get() == "B": 
        entries[0][1]['bg'] = "BLUE"
    

    or

    if entries[0][1].get() == "B": 
        entries[0][1].config(bg="BLUE")
    

    See Entry.config() on effbot.org