Home > database >  Tkinter: 2 buttons next to each other resize in width with window. How to?
Tkinter: 2 buttons next to each other resize in width with window. How to?

Time:12-30

The 2 buttons should take each of the half of the window, one on the left, one on the right. The height is fixed all time. With .grid() nor .place() I can come to that result. The red bar is the color of the frame where the buttons are placed on. The buttons resize in width with the window, but keep their constant height.

How to?

enter image description here

CodePudding user response:

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='red')
frame.pack(fill='both', expand=True)

button1 = tk.Button(frame, text="<<")
button2 = tk.Button(frame, text=">>")

button1.grid(row=0, column=0, sticky='nsew')
button2.grid(row=0, column=1, sticky='nsew')

frame.columnconfigure(0, weight=1)
frame.columnconfigure(1, weight=1)

root.mainloop()

CodePudding user response:

Thx. In the mean time I got this:

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='red',height=30)
frame.pack(fill='both')

button1 = tk.Button(frame, text="<<")
button2 = tk.Button(frame, text=">>")

button1.place(relwidth=0.5, relx=0, relheight=1)
button2.place(relwidth=0.5, relx=0.5, relheight=1)

root.mainloop()

CodePudding user response:

Assuming that the buttons are the only widgets in the frame (ie: you are making a toolbar), I would use pack. grid will also work, but it requires one extra line of code.

Using pack

Here's a version with pack. Notice that the frame is packed along the top and fills the window in the "x" direction. The buttons each are instructed to expand (ie: receive extra, unused space) and to fill the space allocated to them in the "x" direction.

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='red',height=30)
frame.pack(side="top", fill="x")

button1 = tk.Button(frame, text="<<")
button2 = tk.Button(frame, text=">>")

button1.pack(side="left", fill="x", expand=True)
button2.pack(side="right", fill="x", expand=True)

root.mainloop()

Using Grid

A version with grid is similar, but you must use columnconfigure to give a non-zero weight to the two columns:

import tkinter as tk

root = tk.Tk()

frame = tk.Frame(root, bg='red',height=30)
frame.pack(side="top", fill="x")

button1 = tk.Button(frame, text="<<")
button2 = tk.Button(frame, text=">>")

button1.grid(row=0, column=0, sticky="ew")
button2.grid(row=0, column=1, sticky="ew")

frame.grid_columnconfigure((0, 1), weight=1)

root.mainloop()
  • Related