Tried to replace text heading by image heading in ttk.Treeview, but image always align right. How can I align the image to center of heading ?
Here, image is a small blue box for demo only, most of time, the size of image always smaller than column size.
from PIL import Image, ImageTk
from tkinter import Tk, ttk
root = Tk()
font = ('Courier New', 20)
headings = [f'Column {i}' for i in range(3)]
treeview = ttk.Treeview(root, columns=headings, show='headings', height=5)
im = Image.new("RGBA", (20, 20), "#0000ffff")
image = ImageTk.PhotoImage(im)
for heading in headings:
treeview.heading(heading, image=image, anchor='w')
treeview.column(heading, width=200)
style = ttk.Style()
heading_name = "Treeview.Heading"
style.configure(heading_name, font=("Courier New", 40))
treeview.pack()
root.mainloop()
After add style layout, and set ('Treeheading.image', {'side': 'top', 'sticky': ''})
, the image aligned to top center, not on center in both of vertical and horizontal.
from PIL import Image, ImageTk
from tkinter import Tk, ttk
root = Tk()
font = ('Courier New', 20)
headings = [f'Column {i}' for i in range(3)]
treeview = ttk.Treeview(root, columns=headings, show='headings', height=5)
im = Image.new("RGBA", (20, 20), "#0000ffff")
image = ImageTk.PhotoImage(im)
for heading in headings:
treeview.heading(heading, image=image, anchor='w')
treeview.column(heading, width=200)
style = ttk.Style()
heading_name = "Treeview.Heading"
style.layout(heading_name,
[('Treeheading.cell', {'sticky': 'nswe'}),
('Treeheading.border', {'sticky': 'nswe', 'children': [
('Treeheading.padding', {'sticky': 'nswe', 'children': [
('Treeheading.image', {'side': 'top', 'sticky': ''}),
('Treeheading.text', {'sticky': 'we'})
]})
]})
])
style.configure(heading_name, font=("Courier New", 40))
treeview.pack()
root.mainloop()
[Update] Here's the result of my script after I got solution here. Heading not text, but rotated image.
CodePudding user response:
As I pointed out in the comments you can use ttk.Style for this. An exampel can be found below:
from PIL import Image, ImageTk
from tkinter import Tk, ttk
root = Tk()
style = ttk.Style(root)
font = ('Courier New', 20)
headings = [f'Column {i}' for i in range(3)]
treeview = ttk.Treeview(root, columns=headings, show='headings', height=5,
style='my.Treeview')
im = Image.new("RGBA", (20, 20), "#0000ffff")
image = ImageTk.PhotoImage(im)
for heading in headings:
treeview.heading(heading, image=image, anchor='w')
treeview.column(heading, width=200)
treeview.pack()
style.layout('my.Treeview.Heading',
[('Treeheading.cell', {'sticky': 'nswe'}),
('Treeheading.border', {'sticky': 'nswe', 'children': [
('Treeheading.padding', {'sticky': 'nswe', 'children': [
('Treeheading.image', {'side': 'top', 'sticky': '','expand':True}),
('Treeheading.text', {'sticky': 'we'})
]})
]})
])
root.mainloop()
I just changed ('Treeheading.image', {'side': 'right', 'sticky': ''}),