问题
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()
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.
回答1:
You should use bbox
against the root
widget (upon which grid
method was called, not the widget put inside the grid).
print(root.bbox())
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))
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)
method of tkinter.Tk instanceReturn a tuple of integer coordinates for the bounding box of this widget controlled by the geometry manager grid.
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.
The returned integers specify the offset of the upper left corner in the master widget and the width and height. (
help(root.bbox)
)
Alternatively you can use winfo_width and winfo_height:
def getwidth():
print(lbl.winfo_width(), lbl.winfo_height())
来源:https://stackoverflow.com/questions/18461448/how-to-get-the-width-of-tkinter-widget