player1
and player2
are local to the enter()
function and therefore cannot be accessed outside of it. While you could make them global variables that can be referenced by any and all functions, globals are generally considered to be poor way to do things for a variety of reasons. (See Global Variables Are Bad for a specifics about why it's probably a good idea to avoid them.)
One way to sidestep having to do that in Tkinter applications, is make your program more object-oriented and define the main window to be a subclass of its Tkinter.Frame
widget. This is fairly easy to do and then you can then add as many additional attributes to it as needed and reference them from any of its methods via self.xxx
without polluting the global namespace with a bunch of "stuff".
Here's what I mean (note I remove your e1
and e2
variables because they were both being assigned None
(because that's what the pack()
method returns). They weren't being used anywhere else, anyway, which is probably why you never noticed.
from Tkinter import *
class App(Frame):
def __init__(self, title, master=None):
Frame.__init__(self, master) # initialize base class
self.pack()
self.master.title(title)
self.var1 = StringVar()
self.var2 = StringVar()
Label(self, text="Player One: ").pack(side=LEFT)
Entry(self, textvariable=self.var1).pack(side=LEFT)
Label(self, text="Player Two: ").pack(side=LEFT)
Entry(self, textvariable=self.var2).pack(side=LEFT)
Button(self, width=15, text="ENTER", command=self.enter).pack(side=LEFT)
Button(self, width=15, text="PRINT", command=self.printIt).pack(side=LEFT)
def enter(self):
self.player1 = self.var1.get()
self.player2 = self.var2.get()
def printIt(self):
print(self.player1)
print(self.player2)
app = App("Player's Names")
app.mainloop()