Search code examples
python-3.xtkintercolor-schemetkinter-entryinsertion

How to change ttk.Entry insertion cursor color?


I am developing an application using Python3 and tkinter 8.6. Part of is a rather complex dialog which uses a dark background. The enclosed code employs only a few widgets to show the area I can not make work. Among other things my dialog makes obvious (by highlighted background color, just tab) the widget that has keyboard focus. I have tried every possible search string I could come up with for a solution, but to no avail. Turns out the 'insertwidth': '4' does work. The thing I want to so is change the color of the ttkEntry widget insertion point cursor. None of the suggested answers I have found seem to be a solution. Thanks in advance.

    #!/usr/bin/env python3
import tkinter as tk
import tkinter.ttk as ttk    # ttk widgets use styles
import tkinter.font as tkfont

def app_exit():
    root.destroy()


root = tk.Tk()
root.geometry('400x50+400+100')
bg = '#2C2B3B'    # dark blue
hlbg = '#3F3D5C'  # dark blue a shade lighter
fg = 'white'
ebg = 'pink'   # Entry inserts
root.configure(background=bg)  # fills in around labels and entries
font14 = tkfont.Font(size=14)
font10 = tkfont.Font(size=10)
root.option_add('*TEntry*Font', font14)
ttstyle = ttk.Style()
ttstyle.theme_use('default')
ttstyle.theme_settings('default', {
    '.': {   # this sets the general defaults for everybody
        'configure': {'font': font14, 'background': bg, 'foreground': fg}},
    'TButton': {
        'map': {'background': [('active', hlbg), ('focus', hlbg), ('!disabled', bg)]}},
    'TEntry': {  # 'insertforeground' and 'insertforeground' does not seem to do anything
        'configure': {'insertwidth': '4', 'insertforeground': ebg, 'insertforeground': ebg},
        'map': {'fieldbackground': [('active', hlbg), ('focus', hlbg), ('!disabled', bg)],
                'foreground': [('!disabled', fg)]}},
    'TLabel': {
        'configure': {'font': font10}}})

lbl1 = ttk.Label(root, text='Hello ')
tbx = ttk.Entry(root)
btnOK = ttk.Button(root, text='Exit', command=app_exit)

lbl1.grid(row=0, column=0, sticky='w')
tbx.grid(row=0, column=1, sticky='ew')
btnOK.grid(row=0, column=2, sticky='e')
tbx.insert(0,'AbCdEf')
tbx.focus()

root.mainloop()

Example output


Solution

  • The option for a ttk Entry widget is insertcolor.

    ...
    'TEntry': {
        'configure': {..., 'insertcolor': ebg},
    ...
    

    Here is a handy reference of all of the options for ttk widgets. It's on the tcler's wiki so the syntax is tcl rather than python, but the option names themselves are the same between languages.

    Changing Widget Colors