Home > Net >  Why can't change ttk.Entry background color?
Why can't change ttk.Entry background color?

Time:01-13

Here is a code simple to illustrate my problem :

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.geometry('300x300')
s = ttk.Style(root)
s.configure(
    'TEntry',
    background='blue',
    foreground='red'
)
s.map(
    'TEntry',
    foreground=[('focus', 'pink')],
    background=[('focus', 'green')]
)
Entry = ttk.Entry(root)
Entry.pack()
root.mainloop()

No matter what I do the Entry's background stays white. On the other hand, the foreground changes color well. Any idea please ? I'm runing Python 3.11.1 under Windows 11.

CodePudding user response:

Try this.

  • Add layout.
  • Add StringVar()
  • Add fieldbackground

Code:

from tkinter import *
from tkinter import ttk

root = Tk()
root.geometry('300x300')
              
s = ttk.Style()
 
s.layout("EntryStyle.TEntry",
                   [('Entry.plain.field', {'children': [(
                       'Entry.background', {'children': [(
                           'Entry.padding', {'children': [(
                               'Entry.textarea', {'sticky': 'nswe'})],
                      'sticky': 'nswe'})], 'sticky': 'nswe'})],
                      'border':'2', 'sticky': 'nswe'})])

s.configure("EntryStyle.TEntry",
                 background="blue", 
                 foreground="red",
                 fieldbackground="black")

var = StringVar()

e = ttk.Entry(root, style="EntryStyle.TEntry", textvariable=var, font='sans 15 bold')
e.pack(padx=10, pady=10)

root.mainloop()

Screenshot:

enter image description here

  • Related