问题
Right now i have this threecode:
tree["columns"] = ("one", "two", "three")
tree.column("one", width=150)
tree.column("two", width=150)
tree.column("three", width=150)
tree.heading("one", text="Naar")
tree.heading("two", text="Spoor")
tree.heading("three", text="Vetrektijd")
tree['show'] = 'headings'
but what i want to do is change the font size to 20 of the three columns But how can i do that? Since on the internet i read something about Style() but that doesnt work in my code
回答1:
There are two solutions which jump to mind.
The first is the use of Style()
as you pointed out, which will let us set the style of the Treeview.Heading
text if we want to change that.
This looks something like the below:
from tkinter import *
import tkinter.ttk as ttk
root = Tk()
tree = ttk.Treeview(root)
tree.pack()
style = ttk.Style()
style.configure("Treeview.Heading", font=(None, 100))
tree["columns"] = ("one", "two", "three")
tree.column("one", width=150)
tree.column("two", width=150)
tree.column("three", width=150)
tree.heading("one", text="Naar")
tree.heading("two", text="Spoor")
tree.heading("three", text="Vetrektijd")
tree['show'] = 'headings'
This works by styling specific elements inside the widget. Let's break this down.
style = ttk.Style()
tells tkinter that we are creating a style and we're storing it inside of the variable style
.
style.configure()
allows us to configure the style we just created.`
"Treeview.Heading"
is the name of the element for the column headings.
font=(None, 100)
is a "cheaty" way of increasing font size without having to change the font itself. If you wanted to change the font style substitute None
with whichever font you wanted. Perhaps Comic Sans MS
.
The other option is using a function tkinter has built in called nametofont
which let's us mess with the fonts at a deeper level.
We can do something like the below:
from tkinter import *
from tkinter.font import nametofont
import tkinter.ttk as ttk
root = Tk()
tree = ttk.Treeview(root)
tree.pack()
#nametofont("TkHeadingFont").configure(size=100)
tree["columns"] = ("one", "two", "three")
tree.column("one", width=150)
tree.column("two", width=150)
tree.column("three", width=150)
tree.heading("one", text="Naar")
tree.heading("two", text="Spoor")
tree.heading("three", text="Vetrektijd")
tree['show'] = 'headings'
Which seems to achieve the same result, right?
What we're doing differently here is actually modifying the font that tkinter attributes to TkHeadingFont
and telling it to change it's size to 100
. Meaning that if you were to use that font somewhere else it would also appear in the same style.
This involves having to declare from tkinter.font import nametofont
at the top of your program however.
Either method achieves the same result aesthetically speaking.
来源:https://stackoverflow.com/questions/46932332/tkinter-treeview-change-column-font-size