Search code examples
pythontkintertclttk

Tkinter ttk: background/foregound color will not work on my computer


If I run this code via IDLE or a virtual environment in pycharm on both windows 10 and 7:

import tkinter as tk
from tkinter import ttk

x = tk.Tk()
y = ttk.Treeview(x)
y.insert('',0,values=['red', 'blue'], tags= ('even',))
y['columns'] = ('color1','color2')
for item in y['columns']:
    y.heading(item, text=item)
y.tag_configure('even',foreground='yellow',font=('',25))
y.pack()
x.mainloop()

It changes the font but not the background color. This code does work when run from https://repl.it/languages/tkinter and another user pointed out he had success running it from jupyter notebook. The tkinter/tcl versions are identical to the ones on both my computers. But still, I get plain default settings.

This also appears to be consistent across all ttk widgets, such as the combo boxes.

I have tried every theme and messed around with the mapping in the tcl code. Very puzzled as to why I am running into this issue. Has anyone here encountered this? Might be time to switch to pyQT.


Solution

  • A user on a previous question posted this link before he deleted his answer: https://core.tcl-lang.org/tk/tktview/509cafafae48cba46796e12d0503a335f0dcfe0b

    Which led me in the right direction. The fix is to delete some code from the tcl theme source code. Which is found in pythons folder under tcl/ttk. Open the trouble theme(ex.clam, winnative), and find this bit of code:

    ttk::style map Treeview \
            -background [list disabled $colors(-frame)\
                    {!disabled !selected} $colors(-window) \
                    selected $colors(-selectbg)] \
            -foreground [list disabled $colors(-disabledfg) \
                    {!disabled !selected} black \
                    selected $colors(-selectfg)]
    

    the {!disabled !selected} $colors(-window) \ and {!disabled !selected} black \ need to be deleted. cjmcdonald discovered this on the tcl-lang forum. You should end up with:

    ttk::style configure Treeview -background $colors(-window)
        ttk::style map Treeview \
            -background [list disabled $colors(-frame)\
                    selected $colors(-selectbg)] \
            -foreground [list disabled $colors(-disabledfg) \
                    selected $colors(-selectfg)]
    

    The only way I have been able to get this to work is to delete straight from the sourcecode. I am sure someone here can streamline this into python.

    This is only a fix for the Treeview widget and not the others.