Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 920
Mat.C Avatar asked Oct 17 '25 09:10

Mat.C


2 Answers

The proper way to get the width of a single widget is with the winfo_width method. 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. 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.

In your case you can call update before getting the width. This will cause the window to be drawn on the display, resulting in a correct value from winfo_width.

root.update()
print("label width: ", label.winfo_width())
like image 107
Bryan Oakley Avatar answered Oct 18 '25 23:10

Bryan Oakley


    root.geometry("800x600")

http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.winfo_width-method Quoting the link it states: 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. 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).

Returns: The widget’s current width, in pixels.

like image 26
Rahul Avatar answered Oct 18 '25 22:10

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!