3

I only want to allow one character in a TKinter Entry box. How should I do that?

orlp
  • 112,504
  • 36
  • 218
  • 315
  • 3
    possible answer: http://mail.python.org/pipermail/tkinter-discuss/2006-August/000863.html – unutbu Mar 27 '11 at 02:03

3 Answers3

16

Here I am 5 years later :)

from tkinter import *

Window = Tk()
Window.geometry("200x200+50+50") # heightxwidth+x+y

mainPanel = Canvas(Window, width = 200, height = 200) # main screen
mainPanel.pack()

entry_text = StringVar() # the text in  your entry
entry_widget = Entry(mainPanel, width = 20, textvariable = entry_text) # the entry
mainPanel.create_window(100, 100, window = entry_widget)

def character_limit(entry_text):
    if len(entry_text.get()) > 0:
        entry_text.set(entry_text.get()[-1])

entry_text.trace("w", lambda *args: character_limit(entry_text))

you can change this line of code: entry_text.set(entry_text.get()[-1])change the index in the square brackets to change the range

For example: entry_text.set(entry_text.get()[:5]) first 5 characters limit entry_text.set(entry_text.get()[-5:]) last 5 characters limit entry_text.set(entry_text.get()[:1]) first character only entry_text.set(entry_text.get()[:-1]) last character only

Tom Fuller
  • 5,291
  • 7
  • 33
  • 42
2

You can get the string from the entry.get(), verify if len() is greather than 1, and delete char beyond len() that was set. '''

if len(entry.get()) > 1:
    entry.delete(1, END)

''' The number 1 in if statement is your limit. delete() 1 is from where it will start deleting. So everything after 1st char will be deleted.

Leo33
  • 3
  • 2
Lemayzeur
  • 8,297
  • 3
  • 23
  • 50
-3

It's very likely there is a way to do this in tkinter without doing the code yourself but I don't know of it and this should help.

from Tkinter import *
def go():
    text = textbox.get()[0]  #finds the first character
    textbox.delete(0, END)   #deletes everything
    textbox.insert(0, text)  #inserts the first character at the beginning

textbox = Entry(root).pack()
button = Button(root, command=go).pack()