问题
I only want to allow one character in a TKinter Entry box. How should I do that?
回答1:
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
回答2:
You can get the string from the entry.get(), verify if len() is greather than 1, and don't validate it.
回答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()
来源:https://stackoverflow.com/questions/5446553/tkinter-entry-character-limit