问题描述
限时送ChatGPT账号..我正在尝试将小部件的宽度(在本例中为标签)分配给一个变量.
I'm trying to assign the width of a widget (in this case a label) to a variable.
到目前为止我所拥有的:
What I have so far:
from tkinter import *
def getwidth():
print(lbl.bbox())
root = Tk()
lbl = Label(root, text="test text")
lbl.grid(row=0)
btn = Button(root, text="GO", command=getwidth)
btn.grid(row=1)
root.mainloop()
我会假设 bbox()
返回左上角的偏移量以及宽度和高度,但是,返回的值为 {0, 0, 0, 0}代码>.
I would have assumed that bbox()
returns the offset from top left and the width and height, however, the returned value is {0, 0, 0, 0}
.
如果有人能解释为什么会这样,以及正确实现这一目标的步骤是什么,我会很高兴.
If someone could explain why this is and what would be the step to correctly achieve this I would be greatful.
推荐答案
你应该对 root
小部件使用 bbox
(在其上 grid
方法被调用,而不是放在网格内的小部件).
You should use bbox
against the root
widget (upon which grid
method was called, not the widget put inside the grid).
print(root.bbox())
但没有参数,它将给出根小部件的边界框.您需要指定 column
, row
参数(lbl
):
But without argument, it will give root widget's bounding box. You need to specify column
, row
argument (of the lbl
):
print(root.bbox(0, 0))
如果要获取的widget没有定位为0/0列/行,还需要指定col2
、row2
参数.
If the widget you want to get widget not positioned as 0/0 column/row, you need to also specify col2
, row2
argument.
grid_bbox(column=None, row=None, col2=None, row2=None)
方法tkinter.Tk 实例
grid_bbox(column=None, row=None, col2=None, row2=None)
method of tkinter.Tk instance
返回由几何管理器网格控制的此小部件的边界框的整数坐标元组.
Return a tuple of integer coordinates for the bounding box of this widget controlled by the geometry manager grid.
如果 COLUMN, ROW 被给定,则边界框适用于从第 0 行和第 0 列的单元格到指定单元格.如果给定 COL2 和 ROW2,则边界框从该单元格开始.
If COLUMN, ROW is given the bounding box applies from the cell with row and column 0 to the specified cell. If COL2 and ROW2 are given the bounding box starts at that cell.
返回的整数指定主小部件左上角的偏移量以及宽度和高度.(help(root.bbox)
)
The returned integers specify the offset of the upper left corner in the master widget and the width and height. (help(root.bbox)
)
<小时>
或者,您可以使用 winfo_width
和 winfo_height
:
def getwidth():
print(lbl.winfo_width(), lbl.winfo_height())
这篇关于如何获取 tkinter 小部件的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论