问题
In tkinter, I'm trying to make a scrollable canvas that contains widgets so my fixed-size window can scroll to use all the widgets. However, when attempting to set the scrollbar size by getting the bounding box size from the Canvas, None
is returned.
My widgets are being added to the canvas by assigning their parent as the canvas and calling grid()
on each. I try to get the bounding box size after creating and laying out the widgets.
# 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))
should print out some sort of information about the bounding box of the canvas; however, it returns None
.
回答1:
The bbox
method will return a bounding box only for canvas items. If you add a label to the canvas with grid
, it's not a canvas items. You must use one of the methods (create_line
, create_window
, etc) to add an object to the canvas.
(Note that bbox
will return it will show (0, 0, 0, 0) until anything added to the canvas is actually visible on the screen. You need to reset the scroll region either after calling update, or waiting for something like a <Configure>
event.)
来源:https://stackoverflow.com/questions/54222125/canvas-bbox-method-returns-none-although-widgets-exist-inside