0

This should be very very simple but how do I get the following basic code to output the entered variable so that I can then pass it on to the rest of the program.

from Tkinter import *
root = Tk()

InputStrings = StringVar()
Entry(root, textvariable=InputStrings).pack()

def GetString():
    print InputStrings.get()
    Button(root, text='Print', command=OutputText).pack()
    root.mainloop()

def OutputText():
    OutString=InputStrings.get()
    print OutString
    root.withdraw()
    root.quit()

GetString()
print OutString

When I add OutString to the def it gives other errors. Do I really need the OutputText module -can't it just be returned from the GetString module?

GeorgeC
  • 956
  • 5
  • 16
  • 40
  • By the way, `OutputText()` and `GetString()` aren't **modules**, they're **functions**. I think it'd be good to go through a short tutorial on Python. Here's one that I like: [How to Think Like a Computer Scientist](http://openbookproject.net/thinkcs/python/english2e/). – voithos Feb 03 '12 at 07:27
  • 1
    This isn't how tinter (or any event-loop based toolkit) is designed to work. Most of the time the call to start the main loop is the last line of code in the program. It's pretty unusual to start the loop, stop it, and continue on. – Bryan Oakley Feb 03 '12 at 12:16
  • Agree with Bryan, it might make more sense to put the rest of the work needed to be done inside OutputText() or in a function that is called from OutputText() – Niall Byrne Feb 03 '12 at 18:19
  • @Byan and Niall - thanks for the input. I can't call the module at the end because it's a part of an xml metageneration program and I just need these dialogs to collect info from the user to continue to process the xml files -see the full code/purpose @ http://stackoverflow.com/questions/9058867/search-and-replace-multiple-lines-in-xml-text-files-using-python WHAT can/should I use instead of Tkinter? – GeorgeC Feb 05 '12 at 22:38

1 Answers1

2

This is a scope problem! Notice that when you assign to OutString, you're doing it in a function. Well, Python thinks that you want a new variable in that function. But then later, in the module scope, after your call to GetString() is over, you try printing OutString. Surprise! It doesn't exist.

That's because you forgot to add it to the global scope. To make sure that a variable that you assign to is assigned to the global, rather than the local, scope, use the global statement. Like so:

def OutputText():
    # Declare that OutString will be global
    global OutString
    OutString = InputStrings.get()
    ...

GetString()
print OutString
# It prints! Twice, actually, because you also printed it from OutputText()
voithos
  • 68,482
  • 12
  • 101
  • 116