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

问题描述:

所以我一直在研究这个程序,我发现很难弄清楚什么是错的。我对tkinter相当陌生,所以这可能是相当小的。更改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的新手,所以如果我已经看到它,我还没有想出如何实现它。

+0

最后,我有什么要做的是确保颜色变成绿色,红色,黄色取决于条目。 –

请参阅我下面的例子:

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小部件,它包含了widget的内容variable

每次variable更新我们称之为command()try更新entry背景色为entry(IE,红,绿,蓝)和except任何错误的内容,更新的背景,白色的,如果一个异常被提出。


下面是这样做不使用class,并使用单独的testlist检查entry的值的方法:从Tkinter的进口*

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

对不起,这可能是愚蠢的,但我将如何在我的工作中实现这一点,如在哪里以及如何? –

+0

@BhavikNarang我已更新我的回答 –

+0

事情是这是一个输入框,但我如何使它每个输入框单独检查,因为你可以看到我已经使我的表单在循环中 –