仅调整 canvas 宽度不适用于 pack()

Resizing only the canvas width not working with pack()

我的目标是在启动时出现提示,并根据输入的整数,将那么多 canvas 放入框架中。框架必须具有固定的高度(画布也应如此),但宽度应根据 window 的大小而变化,并在 canvas 之间平均分配。

这适用于最多 4 个 canvases,之后 canvases 也不适合最大值 window。

此外,为什么我看不到 canvases 上方和下方的 20 像素空灰色框,因为 canvas 的高度小于框架的高度?

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()

编辑

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()

画布有一个默认大小,它们将尝试成为默认大小。由于 windows 和框架将尝试增大或缩小以容纳其所有子项,因此当默认宽度乘以画布数量超过 window 大小时,主 window 会增大。

解决方案非常简单:给画布一个较小的最小宽度,然后给主 window 一个首选尺寸,然后让画布扩展以填充该区域。

例如:

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

至于为什么上面和下面都看不到space,是因为pack默认是side='top',所以会尽量贴在上面space 它已被放入。

如果要space上下,就用pady,例如:

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