30

Im making a list of addresses that the user will select from, and the address text will be returned. I need to use Tkinter.Label because the Tkinter.Listbox will not allow for newlines.

The kicker is there is no .get()-like method in the Label class...

I know I can do something like:

v = StringVar()
Label(master, textvariable=v).pack()
v.set("New Text!")
 ...
print v.get()

However, I have a list of 5-20 address' keeping a seperate array of StringVar()'s will be difficult b/c I have no way of identifying the loc of the active label. I would like to just access the activated widget contents.

Is Tkinter.Label the right widget to be using?

nbro
  • 15,395
  • 32
  • 113
  • 196
lmno
  • 1,004
  • 1
  • 15
  • 27

2 Answers2

77

To get the value out of a label you can use the cget method, which can be used to get the value of any of the configuration options.

For example:

l = tk.Label(text="hello, world")
...
print("the label is", l.cget("text"))

You can also treat the object as a dictionary, using the options as keys. Using the same example you can use l["text"].

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • 1
    cget() did the trick!!! Im kinda new to Tkinter, but this method seems quite useful! I shall add it to my grimoire. Thanks Again! – lmno May 24 '11 at 17:09
18
label = Label(text = 'Hello, World!')
print(label['text']) # output is: Hello, World!
Yas
  • 4,957
  • 2
  • 41
  • 24
  • 1
    Although this code might solve the problem, an explanation is needed to make it to an answer. – BDL Sep 08 '16 at 13:19