First letters of a Tkinter input First letters of a Tkinter input tkinter tkinter

First letters of a Tkinter input


Your check function will have to retrieve the textfield after the button has been pressed:

def check():    text = inputfield.get()    print text.startswith('sag')

I've changed your test a little, using .startswith(), and directly printing the result of that test (print will turn boolean True or False into the matching string).

What happens in your code is that you define inputfield, retrieve it's contents (obviously empty), and only then show the TKInter GUI window by running the mainloop. The user never gets a chance to enter any text that way.


You can also check this without the need for a button (Now it will check whenever the user presses "Enter"):

from Tkinter import *root = Tk()def check(*event):    text = inputfield.get()    print text.startswith('sag')inputfield = Entry(root)inputfield.bind('<Return>',check)inputfield.pack()root.mainloop()

You can also do other things to have your widget validate the entry as you type. (The link is old, but it also points to newer features that allow you to do this without subclassing).


You're not actually putting the value in the input field into the text variable.

I renamed the value from text to input_text because it was confusing to me. I also changed from using text[0] + text[1] + text[2] to using startswith(). This will keep you from getting IndexErrors on short strings, and is much more pythonic.

from Tkinter import*root = Tk()def check():    input_text = inputfield.get()    if input_text.startswith('sag'):        print "True"    else:        print "False"inputfield = Entry(root)inputfield.pack()input_text = inputfield.get()print input_text # Note that this never prints a string, because it only prints once when the input is empty.but = Button(root, text='Check!', command=check)but.pack()root.mainloop()

The key change is that the check function needs to actually get the value in the inputfield.