简体   繁体   English

我如何在tkinter中获取标签的当前宽度

[英]How do i get the current width of a Label in tkinter

I have a lable within a text and i want to get the current width of the Label 我在文本中有一个标签,我想获取标签的当前宽度

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()

label = tk.Label(root, text="hello world!")
label.pack()

print("label width: ", label.winfo_width())

root.mainloop()

Here is an executable example of my problem, the method .winfo_width() always return 1. Has tkinter a method for get the real width of the label or i have to build it? 这是我的问题的可执行示例,方法.winfo_width()始终返回.winfo_width()有获取标签实际宽度的方法吗?还是我必须构建它?

The proper way to get the width of a single widget is with the winfo_width method. 获取单个窗口小部件宽度的正确方法是使用winfo_width方法。 It will return the width of any widget. 它将返回任何小部件的宽度。

The important thing to know about winfo_width , however, is that it returns the actual width of the rendered widget. 但是,有关winfo_width的重要信息是,它返回渲染的小部件的实际宽度。 If it hasn't been rendered -- either you haven't placed it in a window or the window hasn't had a chance to be drawn -- it will return a width of 1 pixel. 如果尚未渲染(您尚未将其放置在窗口中或没有机会绘制窗口),它将返回1像素的宽度。

In your case you can call update before getting the width. 根据您的情况,您可以在获取宽度之前调用update This will cause the window to be drawn on the display, resulting in a correct value from winfo_width . 这将导致在显示窗口上绘制窗口,从而从winfo_width获得正确的值。

root.update()
print("label width: ", label.winfo_width())
    root.geometry("800x600")

http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.winfo_width-method Quoting the link it states: winfo_width() [#] http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.winfo_width-method引用它指出的链接:winfo_width()[#]

Get the width of this widget, in pixels. 获取此小部件的宽度(以像素为单位)。 Note that if the window isn't managed by a geometry manager, this method returns 1. To you get the real value, you may have to call update_idletasks first. 请注意,如果窗口不是由几何管理器管理的,则此方法返回1。要获取真实值,可能必须先调用update_idletasks。 You can also use winfo_reqwidth to get the widget's requested width (that is, the “natural” size as defined by the widget itself based on it's contents). 您还可以使用winfo_reqwidth获取小部件的请求宽度(即,小部件本身根据其内容定义的“自然”大小)。

Returns: The widget's current width, in pixels. 返回:小部件的当前宽度,以像素为单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM