更改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的新手,所以如果我已经看过它,我还没有弄清楚如何实施它。

请参阅下面的示例:

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(),将try更新entry的背景颜色为entry的内容(即,红色,红色,绿色,蓝色)和except任何错误提起。


下面是一种无需使用class即可使用test list检查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()

相关内容

  • 没有找到相关文章

最新更新