Canvas bbox 方法返回 None 尽管里面存在小部件



在tkinter中,我正在尝试制作一个包含小部件的可滚动画布,以便我的固定大小的窗口可以滚动以使用所有小部件。但是,当尝试通过从画布获取边界框大小来设置滚动条大小时,将返回None

我的小部件

通过将其父小部件指定为画布并在每个小部件上调用grid()来添加到画布中。我尝试在创建和布置小部件后获取边界框大小。

# Create vertical scrollbar
self.scrollbar = Scrollbar(self.master, orient = VERTICAL)
# Pack on the right side and fill on the Y-axis
self.scrollbar.pack(side = RIGHT, fill = Y)
# Create container canvas, set Y-axis scroll command to scrollbar value
self.mainsection = Canvas(self.master, bg = colors["lightgray"], yscrollcommand = self.scrollbar.set)
# Pack on the left side, center, fill and expand on both axes
self.mainsection.pack(side = LEFT, anchor = CENTER, fill = BOTH, expand = True)
# Configure the scrollbar to scroll the canvas.
self.scrollbar.config(command = self.mainsection.yview)
# Widget definitions go here.
self.printsectionlabel = Label(self.mainsection, text = "Print Bills")
self.printsectionlabel.grid(row = 0)
# More widget definitions here...
# Run after all widget definitions
# Creates disabled scrollbar
self.mainsection.configure(scrollregion = self.mainsection.bbox(ALL))
# Prints "None"
print(self.mainsection.bbox(ALL))

print(self.mainsection.bbox(ALL))应该打印出有关画布边界框的某种信息;但是,它返回None

bbox 方法将仅返回画布项的边界框。如果使用 grid 向画布添加标签,则它不是画布项目。您必须使用其中一个方法(create_linecreate_window等)将对象添加到画布。

(请注意,bbox将返回它将显示 (0, 0, 0, 0),直到添加到画布的任何内容在屏幕上实际可见。您需要在调用 update 或等待类似 <Configure> 事件的内容后重置滚动区域。