Python 如何在 tkinter 中找出当前的小部件大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3950687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find out the current widget size in tkinter?
提问by Denilson Sá Maia
I'm using Pythonand Tkinter, and I need to know the current dimensions (width, height) of a widget.
我正在使用Python和Tkinter,我需要知道小部件的当前尺寸(宽度、高度)。
I've tried somewidget["width"], but it returns only a fixed value, and is not updated whenever the widget size changes (e.g. when the window is resized).
我试过somewidget["width"],但它只返回一个固定值,并且不会在小部件大小发生变化时更新(例如,当窗口调整大小时)。
采纳答案by Lie Ryan
Use somewidget.winfo_width()and somewidget.winfo_height()to get the actual widget size, the somewidget['width']property is only a hint given to the geometry manager.
使用somewidget.winfo_width()和somewidget.winfo_height()获取实际的小部件大小,该somewidget['width']属性只是给几何管理器的一个提示。
回答by Apostolos
somewidget.winfo_width()and somewidget.winfo_height()give 1. You need to update Tk (issue tk.update()) before getting these values.
somewidget.winfo_width()并somewidget.winfo_height()给出 1。tk.update()在获取这些值之前,您需要更新 Tk(问题)。
回答by Jose Luis Bracamonte Amavizca
You can use the function somewidget.winfo_reqheight()for height and somewidget.winfo_reqwidth()for width, but first don't forget to call the update function of the widget you want to know the dimension somewidget.update(). If you do not call the update function you will get the default value 1.
您可以使用somewidget.winfo_reqheight()height 和somewidget.winfo_reqwidth()width函数,但首先不要忘记调用您想知道尺寸的小部件的更新函数somewidget.update()。如果您不调用更新函数,您将获得默认值1。

