maaxlength in Entry() / Tkinter

Matthew Dixon Cowles matt at mondoinfo.com
Sun Jul 14 22:54:44 EDT 2002


On Mon, 15 Jul 2002 03:21:40 +0200, Joaquin Romero
<jromero at platea.pntic.mec.es> wrote:

Dear Joaquin,

> I can set an maxlength (max number of characters) in a Entry() in
> Tkinter?

Yes, you can though it's a bit of a nuisance. You need to bind a
routine to the KeyPress event and allow or disallow the character
depending on the number of characters already there. I'll append a
small example.

Regards,
Matt



from Tkinter import *

class mainWin:

  def __init__(self,root):
    self.root=root
    self.entryMaxLen=6
    self.createWidgets()
    return None

  def createWidgets(self):
    self.e=Entry(self.root)
    self.e.pack()
    self.e.bind("<KeyPress>",self.checkContentsLength)
    return None
    
  def checkContentsLength(self,event):
    # Allow some characters even if the field is full.
    # There are probably others that should be allowed
    # that I'm not thinking of right now. Allowing
    # control-h is more complex and outside the scope
    # of this news post <wink>.
    if event.keysym in ("BackSpace","Delete","Tab","Left","Right"):
      return None
    if len(self.e.get())==self.entryMaxLen:
      # Don't allow further processing of this event
      # by Tkinter
      return "break"
    else:
      # Further processing OK
      return None

def main():
  root=Tk()
  mainWin(root)
  root.mainloop()
  return None

if __name__=="__main__":
  main()




More information about the Python-list mailing list