0

I want a Text label in tkinter to constantly check if its worth some value. I would like it to be in a while loop and exit it when the values match. My code doesn't work.

while user_input != str(ans):

            master = Tk()
            master.title("Math")
            master.geometry('400x400')

            eq = generate_equation(stage=current_stage)
            ans = calc(eq) 
            Label(master=master,text=f"score: {score}").grid(row=0,column=2,sticky=W)
            Label(master=master, text=f"{q_num}: {eq}").grid(row=0,column=0 ,sticky=W)

            inputtxt = tkinter.Text(master=master,height = 5, width = 20)
            inputtxt.grid()
            user_input =str(inputtxt.get(1.0,"end-1c"))

            mainloop()
Guy zvi
  • 77
  • 1
  • 6
  • Why not just bind to `""`? Also you shouldn't use `while` loops hen using `tkinter`, unless you know what it can cause. – TheLizzard Sep 10 '21 at 14:27

1 Answers1

2

Try this:

import tkinter as tk

def check(event:tk.Event=None) -> None:
    if text.get("0.0", "end").strip() == "answer":
        # You can change this to something else:
        text.insert("end", "\n\nCorrect")
        text.config(state="disabled", bg="grey70")

root = tk.Tk()

text = tk.Text(root)
# Each time the user releases a key call `check`
text.bind("<KeyRelease>", check)
text.pack()

root.mainloop()

It binds to each KeyRelease and checks if the text in the text box is equal to "answer". If it is, it displays "Correct" and locks the text box, but you can change that to anything you like.

Please note that this is the simplest answer and doesn't account for things like your code adding things to the text box. For that you will need more sophisticated code like this.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31