Python, Tkinter: store content of Entry field into a variable

Dear fellow programmers,

I use Python 2.7 on windows 10 64 bits.

I have an issue with a Tkinter window. In a parent program, I want to save a file and I ask the name of the file in a Tkinter window. My problem is that I don't succeed to get this name outside of the Tkinter window. Here is the Python code:

from Tkinter import *
globalFilename = ""    
class Master:
    def __init__(self, top):
        self.filename = ""
        frame_e = Frame(top)
        frame_e.pack()
        self.t_filename = StringVar()

        entry = Entry(frame_e, textvariable=self.t_filename, bg="white")
        entry.pack()
        entry.focus_force()

        saveButton = Button(frame_e, text="Save", command=self.on_button)
        saveButton.pack(side=BOTTOM, anchor=S)


    def on_button(self):
        self.filename = self.t_filename.get()
        print self.filename
        root.quit()
        root.destroy()        


root = Tk()
root.geometry("100x100+100+50")

M = Master(root)
print M.filename
root.mainloop( )
print M.filename
globalFilename = M.filename
print globalFilename

All print statements in this code give nothing when I enter any text into the Entry textbox. This is not what I expect. If I enter "test" I expect "test" to appear for each print statement (i. e. four times here). I tried to go everywhere on the Internet, I tried various tutorials, I tried to copy various examples, to follow various videos, I just don't succeed in fixing this issue.

Note that this piece of code is embedded into a function called saveGame, which is used in a pygame loop.

Thanks in advance! All the best!

2 answers

  • answered 2018-01-16 23:02 Novel

    Your code works.

    The window is not drawn on the screen until you call mainloop(), so printing M.filename before that point prints an empty string (the initialization value). The mainloop() blocks until the window closes, after which 3 print statements successfully print the value that the user entered into the box.

    You may be interested in the easygui module, which does exactly what your program does except you don't have to make it yourself.

  • answered 2018-01-17 07:18 Glxblt76

    Ok, as other posters told, the above code works in a vacuum. It did not work as embedded in my program because I initialized a duplicate tk() before calling my function and initialize it again. I removed this duplicate and it worked.