Tkinter Label Access
This is my first experience with Python's Tkinter GUI. I want to write a program where the result of an interim calculation is displayed on a label. Later in the program I want to use this result in another calculation by simply clicking on the label.
This is what I have set up for a test:
from Tkinter import *
root = Tk()
label1 = Label(root, text='')
label1.pack(side=TOP)
# do some caculation and format result
pi_approx = 355/113.0
str1 = "%.4f" % (pi_approx) # 3.1416
# show result in label text
label1.config(text=str1)
# more code here
mainloop()
I can bind the label to a mouse click, but can't figure out how to retrieve the label's content. Any advice how to do this? There must be some Tk mavens out there.
Ene Uran
Posting Virtuoso
1,723 posts since Aug 2005
Reputation Points: 625
Solved Threads: 213
If you want to display and later retrieve results from a Tkinter GUI, it would be better to use the Text widget rather than the Label widget. The Text widget is a little more complex, but amongst the many things you can do with it, is the retrieval of the string or part of the string displayed.
Here is an example along the line you described ...
from Tkinter import *
def get_value(event):
# retrieve text widget contents between starting_index and ending_index
# starting_index = "%d.%d" % (line, column) here "1.0"
# note, line starts with 1 and column with 0
# here ending_index = END
txt1 = text1.get("1.0", END)
# do something with string value txt1
print "Value in Text Widget =", txt1 # testing
root = Tk()
text1 = Text(root, height=1, width=25)
text1.pack(side=TOP)
# do some caculation and format result
pi_approx = 355/113.0
str1 = "%.4f" % (pi_approx) # 3.1416
# show result in text widget
text1.insert(INSERT, str1)
text1.bind('<Button-1>', get_value) # bind left mouse click
mainloop()
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
You can get the current text of a tkinter Label via the __getitem__ method, like so:
labelText = 'all your base are belong to us'
testLabel = Label(self.frame, text=labelText)
print 'The text is %s' % testLabel.__getitem__("text")
Hope this helps.
Alex
Even simpler, use the dictionary approachlabel_text = testLabel["text"]
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417