Reputation: 761
I am trying to write a program that has twenty five buttons, when one is pressed, it will read from a text file, store it in a variable, then make the text of the label at the bottom of the page change to the text of the text file. Here is my code so far:
from Tkinter import*
box1 = 'C:/Users/Geekman2/Documents/Tests/box1.txt'
var = StringVar()
var.set("man")
def openfile(filename):
filetxt = (open(filename,"r").read())
#filetxt.set(iletxt)
print filetxt
return filetxt
def Box1():
openfile(box1)
openfile(box1)
donut = Tk()
donut.geometry('450x450')
cupcake = Button(donut,text = "Box #1", command= Box1 )
cupcake.pack()
Whatsin = Label(donut,textvariable = var)
Whatsin.pack(side =BOTTOM)
donut.mainloop()
These two lines are giving me trouble, whenever I uncomment them and try to run the program I get the error "AttributeError: 'NoneType' object has no attribute 'tk'"
var = Stringvar()
var.set("man")
Can anyone tell me what might be the cause of this? I know what the error means, but as far as I can tell it doesn't apply in this situation
Upvotes: 0
Views: 443
Reputation: 4604
StringVar (as well as other Tkinter variable) are wrappers around Tcl variable1. Your error come from creating a StringVar before the Tcl interpreter is initialized.
Thus you might call Tk()
(which perform such initialisation) before creating your variables.
If you look at StringVar constructor signature: __init__(self, master=None, value=None, name=None)
you see that as other Tkinter objects, the constructor accepts a master
as first argument. This master is essentially needed to access the Tcl interpreter. If not provided, there is a fallback to a global Tkinter.Tk
instance _default_root
, which is None
in your case. Asking the Tcl interpreter (field named tk
) on it raise the AttributeError
.
Note that for widgets, not providing master lead to the creation of a default one, but not on variables.
1 the whole Tkinter toolkit is a wrapper around a Tcl toolkit called Tk. Tcl variables allow to be traced, ie bind callback on variable change. Tk heavily use this mechanism and thus, Tkinter has to provide access to Tcl variables.
Upvotes: 0
Reputation: 309919
You need to instantiate an instance of Tk
before you can use StringVar
. Move donut = Tk()
before your lines and it should work.
Upvotes: 3