Reputation: 165
I'm trying to set a global variable to the value entered into a Tkinter Entry field, but I'm getting the following error:
NameError: global name 'HealthEntry' is not defined
Here's the relevant code:
Health = 0
class window(Tk):
def __init__(self, parent):
Tk.__init__(self, parent)
self.parent = parent
HealthEntry = Entry(self)
testButton = Button(self, text = "entry field test", command = self.printHealth)
testButton.grid(row=18, column=3)
def printHealth(self):
Health = HealthEntry.get()
print Health
I've also tried changing HealthEntry.get() to window.HealthEntry.get(), but that doesn't work either. What am I doing wrong?
Upvotes: 1
Views: 50
Reputation: 10631
Because your HealthEntry
is not defined with self so basically he is locally to __init__
method.
change it to: self.HealthEntry
def __init__(self, parent):
Tk.__init__(self, parent)
self.parent = parent
self.HealthEntry = Entry(self)
testButton = Button(self, text = "entry field test", command = self.printHealth)
testButton.grid(row=18, column=3)
def printHealth(self):
Health = self.HealthEntry.get()
print Health
As Padraic wrote in his answer, you might want to use testButton as a class member as well..
Upvotes: 2
Reputation: 180411
Make it an actual attribute and use self.HealthEntry
, you might also want to do the same for testButton self.testButton
:
self.HealthEntry = Entry()
self.testButton = Button(self, text = "entry field test", command = self.printHealth)
self.testButton.grid(row=18, column=3)
def printHealth(self):
Health = self.HealthEntry.get()
print Health
To make it global and accessible outside the init method you would need to use the global keyword in the init method global HealthEntry
but the correct way is to make it an attribute as above.
Upvotes: 1