Python Forum

Full Version: How to restrict characters used in an Entry widget?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I surfed the internet for a long time but all of which I tried did not work.

Here is on of which I tried:

#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# GUI module generated by PAGE version 4.14
# In conjunction with Tcl version 8.6
#    Jun 15, 2018 02:37:37 PM

import sys

try:
    from Tkinter import *
except ImportError:
    from tkinter import *

try:
    import ttk
    py3 = False
except ImportError:
    import tkinter.ttk as ttk
    py3 = True

import unknown_support

def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = Tk()
    top = Converter (root)
    unknown_support.init(root, top)
    root.mainloop()

w = None
def create_Converter(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = Toplevel (root)
    top = Converter (w)
    unknown_support.init(w, top, *args, **kwargs)
    return (w, top)

def destroy_Converter():
    global w
    w.destroy()
    w = None



class Converter:
    
    def SubmitCurrency1(self, event):
        global CurrencyTaken1
        CurrencyTaken1 = Entry.get(self.Entry1)
        #self.Entry1.delete(0, 'end')
        print(CurrencyTaken1)
        
    def SubmitCurrency2(self, event):
        global CurrencyTaken2
        CurrencyTaken2 = Entry.get(self.Entry1_1)
        #self.Entry1_1.delete(0, 'end')
        print(CurrencyTaken2)

    def ConvertCurrency(self, event):
        print(CurrencyTaken1 , CurrencyTaken2)

    def callback(self, Entry1Variable):
        self.var.set(self.var.get().upper())
        self.Entry1Variable.set(self.Entry1Variable.get()[:4])

    def callback2(self, Entry2Variable):
        self.var.set(self.var.get().upper())
        self.Entry2Variable.set(self.Entry2Variable.get()[:4])

    def validate(self, *args):
        if not self.vars.get().isalpha():
            corrected = ''.join(filter(str.isalpha, self.vars.get()))
            self.vars.set(corrected)
 
    def __init__(self, top=None):
        '''This class configures and populates the toplevel window.
           top is the toplevel containing window.'''
        _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
        _fgcolor = '#000000'  # X11 color: 'black'
        _compcolor = '#d9d9d9' # X11 color: 'gray85'
        _ana1color = '#d9d9d9' # X11 color: 'gray85' 
        _ana2color = '#d9d9d9' # X11 color: 'gray85' 

        top.geometry("228x101+504+157")
        top.title("Converter")
        top.configure(background="#d9d9d9")

        self.Entry1Variable = StringVar()
        self.Entry1Variable.trace("w", lambda name, index, mode, Entry1Variable=self.Entry1Variable: self.callback(self.Entry1Variable))         

        self.Entry2Variable = StringVar()
        self.Entry2Variable.trace("w", lambda name, index, mode, Entry2Variable=self.Entry2Variable: self.callback2(self.Entry2Variable))         

        self.var = StringVar()
        self.vars = StringVar()
        
        self.Entry1 = Entry(top, textvariable = self.Entry1Variable)
        self.Entry1.place(relx=0.04, rely=0.1,height=20, relwidth=0.19)
        self.Entry1.configure(background="white")
        self.Entry1.configure(disabledforeground="#a3a3a3")
        self.Entry1.configure(font="TkFixedFont")
        self.Entry1.configure(foreground="#000000")
        self.Entry1.configure(insertbackground="black")
        self.Entry1.configure(width=44)
        self.vars.trace('w', self.validate)

        self.Entry1_1 = Entry(top, textvariable = self.Entry2Variable)
        self.Entry1_1.place(relx=0.04, rely=0.4,height=20, relwidth=0.19)
        self.Entry1_1.configure(background="white")
        self.Entry1_1.configure(disabledforeground="#a3a3a3")
        self.Entry1_1.configure(font="TkFixedFont")
        self.Entry1_1.configure(foreground="#000000")
        self.Entry1_1.configure(highlightbackground="#d9d9d9")
        self.Entry1_1.configure(highlightcolor="black")
        self.Entry1_1.configure(insertbackground="black")
        self.Entry1_1.configure(selectbackground="#c4c4c4")
        self.Entry1_1.configure(selectforeground="black")

        self.Button1 = Button(top)
        self.Button1.place(relx=0.26, rely=0.09, height=24, width=49)
        self.Button1.configure(activebackground="#d9d9d9")
        self.Button1.configure(activeforeground="#000000")
        self.Button1.configure(background="#d9d9d9")
        self.Button1.configure(disabledforeground="#a3a3a3")
        self.Button1.configure(foreground="#000000")
        self.Button1.configure(highlightbackground="#d9d9d9")
        self.Button1.configure(highlightcolor="black")
        self.Button1.configure(pady="0")
        self.Button1.configure(text='''Submit''')
        self.Button1.bind("<Button-1>", self.SubmitCurrency1)
       

        self.Button1_2 = Button(top)
        self.Button1_2.place(relx=0.26, rely=0.38, height=24, width=49)
        self.Button1_2.configure(activebackground="#d9d9d9")
        self.Button1_2.configure(activeforeground="#000000")
        self.Button1_2.configure(background="#d9d9d9")
        self.Button1_2.configure(disabledforeground="#a3a3a3")
        self.Button1_2.configure(foreground="#000000")
        self.Button1_2.configure(highlightbackground="#d9d9d9")
        self.Button1_2.configure(highlightcolor="black")
        self.Button1_2.configure(pady="0")
        self.Button1_2.configure(text='''Submit''')
        self.Button1_2.bind("<Button-1>", self.SubmitCurrency2)

        self.Label1 = Label(top)
        self.Label1.place(relx=0.53, rely=0.1, height=21, width=28)
        self.Label1.configure(background="#d9d9d9")
        self.Label1.configure(disabledforeground="#a3a3a3")
        self.Label1.configure(foreground="#000000")
        self.Label1.configure(text='''USD''')

        self.Label1_3 = Label(top)
        self.Label1_3.place(relx=0.53, rely=0.4, height=21, width=28)
        self.Label1_3.configure(activebackground="#f9f9f9")
        self.Label1_3.configure(activeforeground="black")
        self.Label1_3.configure(background="#d9d9d9")
        self.Label1_3.configure(disabledforeground="#a3a3a3")
        self.Label1_3.configure(foreground="#000000")
        self.Label1_3.configure(highlightbackground="#d9d9d9")
        self.Label1_3.configure(highlightcolor="black")
        self.Label1_3.configure(text='''USD''')

        self.Button2 = Button(top)
        self.Button2.place(relx=0.7, rely=0.08, height=54, width=57)
        self.Button2.configure(activebackground="#d9d9d9")
        self.Button2.configure(activeforeground="#000000")
        self.Button2.configure(background="#d9d9d9")
        self.Button2.configure(disabledforeground="#a3a3a3")
        self.Button2.configure(foreground="#000000")
        self.Button2.configure(highlightbackground="#d9d9d9")
        self.Button2.configure(highlightcolor="black")
        self.Button2.configure(pady="0")
        self.Button2.configure(text='''Convert''')
        self.Button2.configure(width=57)
        self.Button2.bind("<Button-1>", self.ConvertCurrency)

        self.Label2 = Label(top)
        self.Label2.place(relx=0.04, rely=0.69, height=26, width=50)
        self.Label2.configure(background="#d9d9d9")
        self.Label2.configure(disabledforeground="#a3a3a3")
        self.Label2.configure(foreground="#000000")
        self.Label2.configure(text='''Amount''')
        self.Label2.configure(width=50)

        self.Entry2 = Entry(top)
        self.Entry2.place(relx=0.31, rely=0.69,height=20, relwidth=0.63)
        self.Entry2.configure(background="white")
        self.Entry2.configure(disabledforeground="#a3a3a3")
        self.Entry2.configure(font="TkFixedFont")
        self.Entry2.configure(foreground="#000000")
        self.Entry2.configure(insertbackground="black")
        self.Entry2.configure(width=144)


               
    

def Sum(event):
    print("LOL")
    
    


if __name__ == '__main__':
    vp_start_gui()
Notice the "self.vars.trace('w', self.validate)", this is what is not working. It is supposed to make it so that I am not able to type numbers into the Entry but it won't work.

Here is what I want to happen: I want to restrict the user to using only ABCDEFGHIJKLMNOPQRSTUVWXYZ. And they should only be able to use 3 characters.

I tried textvariable and validate but the validate thing was too confusing and I didn't know how to implement this using textvariable.
200+ lines of code for one simple call is more than I want to go through, so this is a simple example of using trace to validate code/
try:
    import Tkinter as tk     ## Python 2.x
    import ttk
except ImportError:
    import tkinter as tk     ## Python 3.x
    from tkinter import ttk

class Converter:
    def __init__(self, top):
        self.vars = tk.StringVar()
        self.vars.trace('w', self.validate)
        self.Entry1 = tk.Entry(top, textvariable = self.vars,
                               width=20).grid()

    def validate(self, *args):
        if not self.vars.get().isalpha():
            corrected = ''.join(filter(str.isalpha, self.vars.get()))
            self.vars.set(corrected)
 
root=tk.Tk()
C=Converter(root)
root.mainloop() 
Thank you for the response my dude, I don't know why but it seems I defined another StringVar apparently, and that was the problem. It didn't occur to me then that the stringvar was not linked to the Entry at all!

Anyways I'm so excited my first every GUI script and my second python script ever is so close to being complete! Dance

I just appended your idea (but with isnumeric instead of isalpha) to the text variable of the entry widget.