Question

I am just trying to make a non-graphic game in Tkinter but am having trouble with the entry widget. How can I wait for "<Return>" to be pressed before printing something?

    from Tkinter import *

    class App:
        def __init__(self, master):

            frame = Frame(master)
            frame.pack()
            f = Frame(master, width=500, height=300)
            f.pack(fill=X, expand=True)

            mt = StringVar()


            menubar = Menu(master)
            menubar.add_command(label="New Game", command=self.new_game)
            menubar.add_command(label="Continue Game", command=self.continue_game)
            master.config(menu=menubar)

            maintext = Label(master, fg="blue", textvariable=mt)
            maintext.pack(side=BOTTOM)
            mt.set("")

            self.e1 = Entry(master)
            self.e1.pack()
            self.e1.bind("<Return>")
            self.e1.lower()


            global mt


        def new_game(self):
            mt.set("What do you want your username to be?")
            self.e1.lift()
            #wait for <Return> to be pressed
                mt.set("Welcome " + self.e1.get())
        def continue_game(self):
            mt.set("Type your username in.")



    root = Tk()

    app = App(root)

    root.mainloop()

I want it to be when I click "New Game" on the top menubar, it shows the entry box and waits for me to type something in, and then click enter. THEN it prints out "Welcome"+(what the person types in). What actually happens is when I click New game, it immediately just prints "Welcome".

By print, I mean aet the Label at the bottom to something else, which is reffered to by "mt.set".

Was it helpful?

Solution

In GUI programs you don't wait* for something to happen, you respond to events. So, to call a function when the user presses return you would do something like:

    self.e1.bind("<Return>", self._on_return)

The above will call the function _on_return when the user presses the return key.

In your specific code you don't really need a StringVar. For example, you could do this:

def __init__(self, master):
    ...
    self.maintext = Label(master, fg="blue")
    ...

def _on_return(self, event):
    self.maintext.configure(text="Welcome, %s" % self.e1.get())

* strictly speaking, you can wait for things, but that's not the right way to write GUI programs except under specific circumstances, such as waiting for a dialog to be dismissed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top