Home > Software engineering >  How to refresh tkinter Threeview for the height of heading
How to refresh tkinter Threeview for the height of heading

Time:09-27

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', 'B1\nB2', 'C1\nC2\nC3']
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 World\n')

def callback():
    treeview.heading('#0', text='\nHello World\n')
    """ 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 World\n'), it doesn't work.

enter image description here

Case 2, remove the # from the line treeview.heading('#0', text='\nHello World\n'), 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.

CodePudding user response:

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

def callback():
    treeview.heading('#0', text='\nHello World\n')
    style = ttk.Style()
    style.configure('Treeview.Heading', foreground='black')
  • Related