【问题标题】:Canvas bbox method returns None although widgets exist inside尽管内部存在小部件,但 Canvas bbox 方法返回 None
【发布时间】:2019-01-17 08:44:45
【问题描述】:

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

【问题讨论】:

  • 您的画布上什么也没有。子小部件不是内容,只有各种 .create_XXXX() 方法生成对 .bbox() 可见的项目。
  • Label(self.mainsection, 更改为myFrame = Frame(...) Label(myFrame,...) mainsection.create_window(0, 0, window=myFrame)

标签: python tkinter tkinter-canvas


【解决方案1】:

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

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

【讨论】:

  • 谢谢,但是使用带有框架的create_window(现在添加了所有小部件)现在会从bbox 方法产生(0, 0, 0, 0)
  • @HewwoCraziness:它将显示 0,0,直到小部件在屏幕上实际可见。您需要在调用update 或等待类似<Configure> 事件之后重置滚动区域。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 2021-03-18
  • 2018-09-27
  • 2017-05-20
相关资源
最近更新 更多