I did this but buttons are not on same row:
button_frame = tk.Frame()
button_frame.pack(side = 'top', fill = 'x')
x = tk.Button(button_frame, text = 'x')
x.pack(side = 'left', ipadx = 3, ipady = 1)
y= tk.Button(button_frame, text = 'y')
y.pack(side = 'top', ipadx = 3, ipady = 1)
z= tk.Button(button_frame, text = 'z')
z.pack(side = 'right', ipadx = 3, ipady = 1)
I also tried to position every button with side = 'left'
padx = (0, number)
but it works on only my own screen resolution.
CodePudding user response:
You can get what you want using .pack()
, but the order of packing the buttons matters:
x = tk.Button(button_frame, text='x')
y = tk.Button(button_frame, text='y')
z = tk.Button(button_frame, text='z')
# pack left and right first
x.pack(side='left')
z.pack(side='right')
# then pack top
y.pack(side='top')
However I would suggest to use grid()
instead:
x = tk.Button(button_frame, text='x')
y = tk.Button(button_frame, text='y')
z = tk.Button(button_frame, text='z')
button_frame.columnconfigure(1, weight=1)
x.grid(row=0, column=0)
y.grid(row=0, column=1)
z.grid(row=0, column=2)
CodePudding user response:
This script using grid() is one way to place the three buttons on one row with buttons anchored left, center, and right. The self.columnconfigure statements for columns 0 and 2 are not necessary for the proportional resizing, but may be useful for additional widget layout methods.
Using sticky in combination with columnspan and columnconfigure controls where the buttons are positioned in relation to the button_frame as the window resizes.
import tkinter as tk
class CenterButtons(tk.Tk):
def __init__(self):
super().__init__()
self.grid()
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(2, weight=1)
self.xyz_buttons()
@staticmethod
def xyz_buttons():
"""Keep buttons evenly spaced with window resizing."""
button_frame = tk.Frame()
button_frame.grid(row=0, column=0, columnspan=3, sticky=tk.EW)
button_frame.columnconfigure(1, weight=1)
x = tk.Button(button_frame, text='x')
y = tk.Button(button_frame, text='y')
z = tk.Button(button_frame, text='z')
x.grid(row=0, column=0, pady=3, padx=3, sticky=tk.W)
y.grid(row=0, column=1, pady=3, padx=3)
z.grid(row=0, column=2, pady=3, padx=3, sticky=tk.E)
if __name__ == "__main__":
app = CenterButtons()
app.minsize(125, 40)
app.mainloop()