Python: How do i store a text input from the user on Tkinter?
You can make a global variable to hold the input:
inp = None
and then have your function update that variable:
def userinput(): global inp a = raw_input(v.get()) print a inp = a
So, your code will look like this:
master = Tk()master.title('Title')v = StringVar()# Variable to hold the inputinp = NoneL1 = Label(master, text = 'Name')L1.pack(side = LEFT)E1 = Entry(master, textvariable = v, bd = 5)E1.pack(side = RIGHT)def userinput(): # Declare 'inp' to be global global inp a = raw_input(v.get()) print a # Update the variable inp = ab = Button(master, text = 'Submit', command = userinput)b.pack(side = BOTTOM)master.mainloop()
In the above code, inp
will always be a fresh copy of the input which you can use elsewhere in the code.
However, it might be worthwhile to look into making your code a class. That way, you can have a class attribute named self.inp
and you won't have to do global inp
.
As others say - use globe
Example using class
from Tkinter import *class MainWindow(): def __init__(self, master): self.master = master self.master.title('Title') self.v = StringVar() self.L1 = Label(self.master, text = 'Name') self.L1.pack(side = LEFT) self.E1 = Entry(self.master, textvariable = self.v, bd = 5) self.E1.pack(side = RIGHT) self.B1 = Button(self.master, text = 'Submit', command = self.userinput) self.B1.pack(side = BOTTOM) self.B2 = Button(self.master, text = 'Print', command = self.print_external_variable) self.B2.pack(side = TOP) #------------------ def userinput(self): global external_variable external_variable = raw_input(self.v.get()) #external_variable = self.v.get() print "inside - userinput:", external_variable #------------------ def print_external_variable(self): # you don't need global if you don't change external_variable print "inside - print:", external_variable#----------------------------------------------------------------------external_variable = '- none -'print "before run:", external_variablemaster = Tk()MainWindow(master)master.mainloop()print "after run:", external_variable