Enrique Metner
Enrique Metner

Reputation: 189

tkinter: finding optional arguments of a widget

So I created a label widget and gave it the keyword arguments 'width' and 'text'. I want to retrieve the values set to those arguments using the button with the command 'find_text' which then pack those values in the screen. Can you explain why winfo_width() does not return the same value as I set to the width keyword of the label? Is the value the width of the pixels? In any case how do I get the value which I assigned (50)? Also how do I get the text which I assigned to that label? Ofcourse the method I used does not exist but it is for demonstration to show what I want.

from tkinter import *

def find_text():
    widthlabel = Label(root, text=label.winfo_width())
    widthlabel.pack()
    textlabel = Label(root, text=label.winfo_text())
    textlabel.pack()

root = Tk()
root.geometry("500x500")
root.configure(bg="black")

label = Label(root, width=50, text="hello")
label.pack()

button = Button(root, text="find_text_button", command=find_text)
button.pack()

root.mainloop()

Upvotes: 1

Views: 243

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 386265

Can you explain why winfo_width() does not return the same value as I set to the width keyword of the label?

winfo_width() returns the actual width. The actual width is affected by whether it's visible or not, as well as by geometry manager options (eg: the geometry manager may shrink or grow it from it's configured size). If tkinter hasn't had the chance to update the display, or you haven't added the widget to the display, the actual width will be zero.

In short, the actual width isn't necessarily the configured width.

If you want the configured event, you use cget, such as label.cget("width").

Upvotes: 1

Delrius Euphoria
Delrius Euphoria

Reputation: 15098

There are 2 ways I would do this.

  • By using cget() method:
def find_text():
    widthlabel = Label(root, text=label.cget('width')) #get the value of option width
    widthlabel.pack()
    textlabel = Label(root, text=label.cget('text')) #get the value of option text
    textlabel.pack()
  • The next is a simple property indexing, like:
def find_text():
    widthlabel = Label(root, text=label['width']) #returns the width value given
    widthlabel.pack()
    textlabel = Label(root, text=label['text']) #returns the text value given
    textlabel.pack()

Upvotes: 1

Related Questions