Changing entry box background colour in tkinter
Asked Answered
P

1

6

So I've been working on this program and I'm finding it very hard to figure out what's wrong. I'm fairly new to tkinter so this may be quite minor.

I'm trying to get the program to change the entry box's background colour when the check button is pressed. Or even better if somehow I can change it dynamically it would be even better.

This is my code at the moment:

TodayReading = []
colour = ""
colourselection= ['green3', 'dark orange', "red3"]
count = 0

def MakeForm(root, fields):
    entries = []
    for field in fields:
        row = Frame(root)
        lab = Label(row, width=15, text=field, font=("Device",10, "bold"), anchor='center')
        ent = Entry(row)
        row.pack(side=TOP, padx=5, fill=X, pady=5)
        lab.pack(side=LEFT)
        ent.pack(side=RIGHT, expand=YES, fill=X)
        entries.append((field, ent))
    return entries

def SaveData(entries):
    import time
    for entry in entries:
        raw_data_point = entry[1].get()
        data_point = (str(raw_data_point))
        TodayReading.append(data_point)
    c.execute("CREATE TABLE IF NOT EXISTS RawData (Date TEXT, Glucose REAL, BP INTEGER, Weight INTEGER)")
    c.execute("INSERT INTO RawData (Date, Glucose, BP, Weight) VALUES (?, ?, ?, ?)", (time.strftime("%d/%m/%Y"), TodayReading[0], TodayReading[1] , TodayReading[2]))
    conn.commit()
    conn.close()

def DataCheck():
    if ((float(TodayReading[0])>=4 and (float(TodayReading[0])<=6.9))):
        colour = colourselection[count]
        NAME OF ENTRY BOX HERE.configure(bg=colour)

Thanks for the help. Someone may have answered it already but like i said I'm new to tkinter so if i've seen it already, I haven't figured out how to implement it.

Poliomyelitis answered 3/9, 2017 at 18:48 Comment(1)
In the end, what i have to do is make sure the colours change to green, red, yellow depending on the entry.Poliomyelitis
P
9

Please see my example below:

from tkinter import *

class App:
    def __init__(self, root):
        self.root = root
        self.var = StringVar() #creates StringVar to store contents of entry
        self.var.trace(mode="w", callback=self.command)
        #the above sets up a callback if the variable containing
        #the value of the entry gets updated
        self.entry = Entry(self.root, textvariable = self.var)
        self.entry.pack()
    def command(self, *args):
        try: #trys to update the background to the entry contents
            self.entry.config({"background": self.entry.get()})
        except: #if the above fails then it does the below
            self.entry.config({"background": "White"})

root = Tk()
App(root)
root.mainloop()

So, the above creates an entry widget and a variable which contains the contents of that widget.

Every time the variable is updated we call command() which will try to update the entry background colour to the contents of the entry (IE, Red, Green, Blue) and except any errors, updating the background to White if an exception is raised.


Below is a method of doing this without using a class and using a separate test list to check the value of the entry: from tkinter import *

root = Tk()

global entry
global colour

def callback(*args):
    for i in range(len(colour)):
        if entry.get().lower() == test[i].lower():
            entry.configure({"background": colour[i]})
            break
        else:
            entry.configure({"background": "white"})


var = StringVar()
entry = Entry(root, textvariable=var)
test = ["Yes", "No", "Maybe"]
colour = ["Red", "Green", "Blue"]
var.trace(mode="w", callback=callback)

entry.pack()
root.mainloop()
Pessimism answered 4/9, 2017 at 9:2 Comment(4)
Sorry this may be stupid, but how would i implement this within my work, as in where and how?Poliomyelitis
Thing is this is one entry box but how do i make it so that each entry box is checked separately because as you can see i've made my form in a loopPoliomyelitis
You can create a list of stringvar s and assign each to the entry widget and then trace when any of the stringvars are updated in the same way.Pessimism
This is probably really frustrating but could you maybe write some code for this so i understand it betterPoliomyelitis

© 2022 - 2024 — McMap. All rights reserved.