5

My code looks something like this

from Tkinter import *
import tkMessageBox
import Tkinter

top = Tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()

C1 = Checkbutton(top, text = "Music", variable = CheckVar1, onvalue = 1,  offvalue = 0 )
C2 = Checkbutton(top, text = "Video", variable = CheckVar2,onvalue = 1, offvalue = 0 )

I have created two checkbuttons with values and some text. If I want to print the values of the checkbuttons i use this code:

print CheckVar1.get()
print CheckVar2.get()

But I also want to print the text of the Checkbutton. I tried to the following:

print C1.get("text")
print C2.get("text)

Which does not work at all.Is there some trick for this? Or do I have to create some workaround like this: (Which seems quite strange)

 CheckVar1 = IntVar()
 CheckVar2 = IntVar()
 Name1 =  StringVar(value="Music")
 Name2 =  StringVar(value="Video")

 C1 = Checkbutton(top, text = Name1, variable = CheckVar1, onvalue = 1,  offvalue = 0 )
 C2 = Checkbutton(top, text = Name2, variable = CheckVar2,onvalue = 1, offvalue = 0 )

print Name1
print Name2

Thank you in advance ;)

nieka
  • 259
  • 1
  • 4
  • 14
  • @Kevin thank you. I forgot to mention that i added the `grid` function, which returned me `None` all the time. Now I split my checkbuttons like this `C1 = ... ` and `C1.grid(....)` and now the `cget()` function works! Thank you – nieka Nov 05 '15 at 13:19
  • Why do you want to get the text from the UI? That's a code smell. UIs are not for storing values but for communicating with the user. – BlackJack Nov 05 '15 at 15:25

1 Answers1

9
print C1.get("text")
print C2.get("text")

To get the value of a widget's attribute, try using cget.

print C1.cget("text")
print C2.cget("text")
Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • I tried this as well and get the following error: print self.C1.cget("text") AttributeError: 'NoneType' object has no attribute 'cget' – nieka Nov 05 '15 at 13:11
  • Are you doing `C1 = CheckButton(...).pack()` when creating the widget? That makes it impossible to access its attributes. See [Tkinter: AttributeError: NoneType object has no attribute get](http://stackoverflow.com/q/1101750/953482) for more information. – Kevin Nov 05 '15 at 13:33