2

I started learning python a month and a half ago. So please forgive my lack of everything.

I'm making a text based adventure game. The game has been written and playable in terminal. I'm now adding a GUI as an after thought.

In one file, I have:

class Parser():

    def __init__(self):
        self.commands = CommandWords()

    def get_command(self):
        # Initialise word1 and word2 to <None>
        word1 = None
        word2 = None

        input_line = input( "> " )

        tokens = input_line.strip().split( " " )
        if len( tokens ) > 0:
            word1 = tokens[0]
            if len( tokens ) > 1:
                word2 = tokens[1]

This is called whenever the user is expected to enter text, it will then call another function to compare the input with known commands to move the game along.

However, when I tried to replace the input() with entry_widget.get(), it doesn't recognise entry_widget. so I imported my file containing the GUI script, which is a circular importing error.

I tried to store the input as a string variable, but the program doesn't stop and wait for the user input, so it gets stuck the moment the program start to run not knowing what to do with the empty variable. (that is assuming input() stops the program and wait for user input? )

Any solutions? Or better ways of doing this?

Thanks.

Bowman C.
  • 31
  • 4
  • First you have to understand [Event-driven programming](https://stackoverflow.com/a/9343402/7414759), [Is this bad programming practice in tkinter?](https://stackoverflow.com/questions/25454065/is-this-bad-programming-practice-in-tkinter), [Best way to structure a tkinter application](https://stackoverflow.com/a/17470842/7414759) – stovfl Dec 01 '19 at 19:49

1 Answers1

0

import tkinter as tk

To create an Entry widget: entry = tk.Entry(root)

After you have that, you can get the text at any time: text = entry.get()

To make the program wait you need to create a tkinter variable: wait_var = tk.IntVar()

and then create a button that changes the value of the variable when pressed: button = tk.Button(root, text="Enter", command=lambda: wait_var.set(1))

Now you can tell tkinter to wait until the variable changes:button.wait_variable(wait_var)

Simple example:

import tkinter as tk


def callback():
    print(entry.get())
    wait_var.set(1)


root = tk.Tk()

wait_var = tk.IntVar()

entry = tk.Entry(root)
button = tk.Button(root, text="Enter", command=callback)

entry.pack()
button.pack()

print("Waiting for button press...")
button.wait_variable(wait_var)
print("Button pressed!")

root.mainloop()

ItayMiz
  • 669
  • 1
  • 7
  • 14