Canvas bbox 方法 returns None 尽管内部存在小部件

Canvas bbox method returns None although widgets exist inside

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

我的小部件被添加到 canvas,方法是将它们的父级指定为 canvas 并在每个小部件上调用 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)) 应该打印出关于 canvas 边界框的某种信息;然而,它 returns None.

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

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