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 ;)

2
  • @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 Commented Nov 5, 2015 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. Commented Nov 5, 2015 at 15:25

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this as well and get the following error: print self.C1.cget("text") AttributeError: 'NoneType' object has no attribute 'cget'
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 for more information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.