I'm trying to justify (align) text in a button, let's say to the left. I've found some useful code here, based on that I've created code below to check how the label behaves.
import tkinter as tk
import tkinter.ttk as ttk
app = tk.Tk()
style = ttk.Style()
style.layout(
'Left1.TButton',[
('Button.button', None),
('Button.focus', {'children': [
('Button.padding', {'children': [
('Button.label', {'side' : 'left'}
)]}
)]}
)]
)
print("TButton.label->justify: ", style.lookup('TButton.label', 'justify'))
print("TButton.label->side: ", style.lookup('TButton.label', 'side'))
style.configure('TButton.label', justify='left')
style.configure('TButton.label', side='left')
print("TButton.label->justify: ", style.lookup('TButton.label', 'justify'))
print("TButton.label->side: ", style.lookup('TButton.label', 'side'))
ttk.Button(text="TButton", width=100, style="TButton").pack()
ttk.Button(text="Lef1.TButton", width=100, style="Left1.TButton").pack()
print("TButton.label options:\n", style.element_options('TButton.label'))
Problem is that there's no effect on the label. It stays in the center of the button. What is even more interesting is last line. Output is:
TButton.label options:
('compound', 'space', 'text', 'font', 'foreground', 'underline', 'width', 'anchor', 'justify', 'wraplength', 'embossed', 'image', 'stipple', 'background')
But if I try to set 'anchor' I'm getting exception. I know this feature is absent in ttk but why is it showing up here?
I've just been using the following style and it's working - this applies the anchor='center' configuration to all of my buttons, but you can create your own style for each wherein you just change 'TButton' to '{insert your style name}.TButton' (more on that https://www.pythontutorial.net/tkinter/ttk-style/ - underrated resource to learn ttk styling).
Anyways, here's the code:
style = ttk.Style()
style.theme_create( "button-center", parent="alt", settings={
"TButton": {"configure": {"anchor": "center"}}} )
# Now just create the button itself
style.theme_use("button-center")
btn = ttk.Button({the_frame_it_belongs_to})
btn.configure(text='BUTTON', width='15')
btn.grid(column='0', row='0')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With