How to refresh tkinter Threeview for the height of heading

Question:

Try to set heading of Treeview to 3-line height. Following code to demo this issue.

import tkinter as tk
from tkinter import ttk
from tkinter.font import Font

root = tk.Tk()

font = ('Courier New', 10)
tkfont = Font(family=font[0], size=font[1])
width, height = tkfont.measure('W'), tkfont.metrics("linespace")

headings = ['A1', 'B1nB2', 'C1nC2nC3']
data = [('A', [1,2,3]), ('B', [2,4,6]), ('C', [3,6,9])]

treeview = ttk.Treeview(root, columns=headings, displaycolumns=headings,
    show='tree headings', height=4)
for i, heading in enumerate(headings):
    treeview.heading(heading, text=heading)
    treeview.column(heading, width=width*4, minwidth=10, anchor=tk.CENTER)
for i, (text, value) in enumerate(data):
    treeview.insert('', i, text=text, value=value)
treeview.pack()

#treeview.heading('#0', text='nHello Worldn')

def callback():
    treeview.heading('#0', text='nHello Worldn')
    """ Add following statement(s) still not work
    treeview.update()
    treeview.update_idletasks()
    root.update()
    root.update_idletasks()
    """

button = tk.Button(root, text='Change', command=callback)
button.pack()

root.mainloop()

Case 1, use button Change to call #treeview.heading('#0', text='nHello Worldn'), it doesn’t work.

enter image description here

Case 2, remove the # from the line treeview.heading('#0', text='nHello Worldn'), it work.

enter image description here

My question here is

  • what’s the difference for these two cases, and
  • How to refresh the Treeview in case 1 to get same result as in case 2.
Asked By: Jason Yang

||

Answers:

I got one method for it, set the style for treeview widget, and it work.

def callback():
    treeview.heading('#0', text='nHello Worldn')
    style = ttk.Style()
    style.configure('Treeview.Heading', foreground='black')
Answered By: Jason Yang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.