Home > Blockchain >  Tkinter - How to check if an input text equals a specified string
Tkinter - How to check if an input text equals a specified string

Time:10-09

Heyy! Im working on a bigger code, and I would like to get a text from the user, and check if the user entered the correct word(s). Using an Entry box is not an option unfortunately, because the answer might be several rows long... A shortened code is linked down below. Thank you in advance :)

from tkinter import *

window=Tk()

def checking():
    if text.get(1.0,END) == 'correct':
        print('YESS')
    else:
        print('NOOOO')
        print(text.get(1.0,END))

text=Text(window)
gomb=Button(window, command=checking, text='Check')
text.insert(1.0,'correct')

text.pack()
gomb.pack()

window.mainloop()

CodePudding user response:

The Text widget automatically adds a newline at the very end of the data in the widget. When you do text.get(1.0,END) you get this extra newline. To get only the data that was entered by the user or entered by your program, use the string "end-1c" ("end" minus one character).

if text.get("1.0", "end-1c") == "correct"
   ...

Depending on how strict or loose you want the comparison to be, you might want to consider stripping all whitespace at the start and the end, in case the user accidentally pressed the space and didn't realize it:

data = text.get("1.0", "end-1c").strip()
if data == "correct":
    ...

Note: text indexes are not floating point numbers. They are a string of the form line.character. Some floating point numbers will work (for example, 1.0 works as the start of the data) but others won't. For example, the floating point number 1.10 is treated the same as 1.1. It's best to get in the habit of always using strings.

  • Related