在tkinter中更改输入框背景颜色

时间:2017-09-03 18:48:19

标签: python-3.x tkinter background-color tkinter-entry

所以我一直在研究这个项目,我发现很难弄清楚什么是错的。我对tkinter很新,所以这可能很小。

我试图让程序在按下复选按钮时更改输入框的背景颜色。或者甚至更好,如果以某种方式我可以动态地改变它,它会更好。

这是我目前的代码:

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)

感谢您的帮助。有人可能已经回复了,但就像我说我是tkinter的新人所以如果我已经看过它,我还没有想出如何实现它。

1 个答案:

答案 0 :(得分:1)

请参阅下面的示例:

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()

因此,上面创建了一个entry窗口小部件和一个variable,其中包含该窗口小部件的内容。

每次更新variable时,我们都会调用command() tryentry背景颜色更新为entry的内容(IE,红色,绿色,蓝色)和except任何错误,如果引发异常,将背景更新为白色。

以下是一种不使用class并使用单独的test list来检查entry的值的方法:     来自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()