Leo
Leo

Reputation: 111

First letters of a Tkinter input

My program should check if the first three letters of the input word are similar to a predefined word.
I've made a GUI with Tkinter and want to get the letters of the input field.
Somehow I can't implement it in like I would do without Tkinter.

That's how I do it just for the shell:

text = raw_input('Enter a word: ')

if (text[0] + text[1] + text[2] == 'sag'):
    print "sagen"
else:
    print "error"

So, when I input the word "sagst" it checks the first three letters and should put out "sagen". Works fine.

I learned that e.g. inputfield.get() gets the input of the entry "inputfield".
But how can I check the first letters of that "inputfield"?
A small selection:

from Tkinter import*
root = Tk()

def check():
    if (text[0] + text[1] + text[2] == 'sag'):
        print "True"
    else:
        print "False"

inputfield = Entry(root)
inputfield.pack()

but = Button(root,text='Check!', command = check)
but.pack()

text = inputfield.get()

root.mainloop()

Does not work...

I hope you can understand my question and will answer soon. (Sorry for my bad english and my bad Python skills) ;-)
Thanks!

Upvotes: 3

Views: 1818

Answers (4)

unutbu
unutbu

Reputation: 879471

Here is a version which uses an Entry widget which validates its contents as the user types (so the user does not have to click a button or even press Return).

import Tkinter as tk
class MyApp(object):
    '''
    http://effbot.org/zone/tkinter-entry-validate.htm
    http://effbot.org/tkinterbook/entry.htm
    http://www.tcl.tk/man/tcl8.5/TkCmd/entry.htm#M-validate
    '''
    def __init__(self, master):
        vcmd = (master.register(self.validate),
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.entry = tk.Entry(master, validate = 'key',
                              validatecommand = vcmd)
        self.entry.pack()
        self.entry.focus()

    def validate(self, action, index, value_if_allowed,
                   prior_value, text, validation_type, trigger_type, widget_name):
        dtype = {'0':'delete', '1':'insert', '-1':'other'}[action]
        n = min(3, len(value_if_allowed))
        valid = False
        if dtype == 'insert':
            if value_if_allowed[:n] == 'sag'[:n]: valid = True
            else: valid = False
        else: valid = True
        print(valid)
        return True

root = tk.Tk()
app = MyApp(root)
root.mainloop()

Upvotes: 0

mgilson
mgilson

Reputation: 309919

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).

Upvotes: 2

jgritty
jgritty

Reputation: 11915

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.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121834

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.

Upvotes: 3

Related Questions