Home > OS >  tkinter align button within frame with grid()
tkinter align button within frame with grid()

Time:09-22

I'm creating small scratchpad app. The entire app is single column and 3 rows. The row0 will have a close button aligned to the right, row1 is the Text area and row2 will have a few buttons to format the text 1 button to delete/clear the text area. I want that delete/clear button to align to the right while the rest of the buttons will align to the left such that there's a space between the format buttons and the delete button. So that you don't accidentally clear the text. Here is the code:

import tkinter as tk
from tkinter import ttk

wn = tk.Tk()
wn.attributes('-type', 'splash')
style = ttk.Style()
style.configure('top.TFrame', border=0, borderwidth=0, background='green')
style.configure('bottom.TFrame', border=0, borderwidth=0, background='blue')
style.configure('button.TButton', border=5, borderwidth=5, background='#e6e497', bd=5)

root = ttk.Frame(wn, style='top.TFrame', borderwidth=5, relief='ridge')
button = ttk.Button(root, text='X', width=3, command=lambda: wn.destroy(), style='button.TButton')
txt = tk.Text(root, width=40, background='light yellow', bd=5)

bottom = ttk.Frame(root, style='bottom.TFrame', width=2000, borderwidth=5, relief='ridge')
bottombuttona = ttk.Button(bottom, width=3, text='A')
bottombuttonb = ttk.Button(bottom, width=3, text='B')
bottombuttonc = ttk.Button(bottom, width=3, text='C')
bottombuttond = ttk.Button(bottom, width=3, text='D')
bottombuttone = ttk.Button(bottom, width=3, text='E')

root.grid()
button.grid(column=0, row=0, sticky=tk.E, ipady=4)
txt.grid(column=0, row=1, sticky=tk.NSEW)
bottom.grid(column=0, row=2, sticky=tk.NSEW)

bottombuttona.grid(column=0, row=2, ipady=5)
bottombuttonb.grid(column=1, row=2, ipady=5)
bottombuttonc.grid(column=2, row=2, ipady=5)
bottombuttond.grid(column=3, row=2, ipady=5)
bottombuttone.grid(column=4, row=2, ipady=5, sticky=tk.E)

txt.focus_force()
wn.bind('<Escape>', lambda x: wn.destroy())
wn.mainloop()

This is the result:

enter image description here

Question: How do I move the bottombuttone (E) to the right of the bottom frame it is in (blue colored)? sticky doesn't seem to work

secondary question: what's the purpose of the width option in the Frame class? doesn't seem to have any impact on the size of the frame itself, despite setting it to 2000.

CodePudding user response:

You can use grid_columnconfigure to get it to work:

...
bottombuttond.grid(column=3, row=2, ipady=5)
bottom.grid_columnconfigure(4, weight = 1)
bottombuttone.grid(column=4, row=2, ipady=5, sticky=tk.E)
...

Setting the weight of the last item to 1 allows it to expand to fill it's parent. Using sticky = tk.E, it will stick to the right of it's parent.

I made this to demonstrate how grid weights work. The blue is the parent, C1-3 are the child widgets. Example of tkinter weight

  • Related