stochastic13
stochastic13

Reputation: 423

Resizing only the canvas width not working with pack()

My aim is to have a prompt go at the startup, and based on the entered integer, have those many canvases fit in the frame. The frame must have a fixed height (and so should the Canvases), but the width should vary depending on the size of the window and be distributed equally among the canvases.

This works well with upto 4 canvases, after which the canvases do not fit into the max window also.

Plus, why am I not able to see the 20-pixel empty gray frame above and below the canvases, since the height of the canvas is lesser than that of the frame?

from tkinter import *
from tkinter import simpledialog

b=[]
root = Tk()
no_of_players=simpledialog.askinteger(prompt="Enter here", title="No of participants")

status_frame=Frame(root, bg='gray', height=100)
status_frame.pack(fill=X)
for i in range(no_of_players):
    c=Canvas(status_frame,  bg="orange")
    b.append(c)
    b[i].pack(side=LEFT,fill=X, expand=True)
root.mainloop()

EDIT

from tkinter import *
from tkinter import simpledialog

b=[]
root = Tk()
no_of_players=simpledialog.askinteger(prompt="Enter here", title="No of participants")

status_frame=Frame(root, bg='gray', height=500)
status_frame.pack(fill=X)
for i in range(no_of_players):
    c=Canvas(status_frame, width=1, height=100, bg="orange")
    b.append(c)
    b[i].pack(side=LEFT,fill=X, expand=True)
root.mainloop()

Upvotes: 0

Views: 639

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385900

Canvases have a default size that they will try to be. Since windows and frames will attempt to grow or shrink to accommodate all their children, the main window grows when the default width times the number of canvases exceeds the window size.

The solution is pretty simple: give the canvases a small minimum width, then give the main window a preferred size, and let the canvases expand to fill the area.

For example:

...
root.geometry("400x100")
...
for i in range(no_of_players):
    c=Canvas(..., width=1)
    ...
...

As for why you don't see space above and below, it's because the default for pack is side='top', so it's going to try to stick to the top of the space it has been put in.

If you want space above and below, use pady, for example:

status_frame.pack(fill=x, pady=20)

Upvotes: 2

Related Questions