Python Tkinter: Delete the Last Character of a String
Asked Answered
B

2

6

I am making an entry that only allows numbers to be entered. I am currently stuck on deleting the character just entered if it that character is not a integer. If someone will replace the the "BLANK" with what needs to go in there it would be a lot of help.

import Tkinter as tk

class Test(tk.Tk):

    def __init__(self):

        tk.Tk.__init__(self)

        self.e = tk.Entry(self)
        self.e.pack()
        self.e.bind("<KeyRelease>", self.on_KeyRelease)

        tk.mainloop()



    def on_KeyRelease(self, event):

        #Check to see if string consists of only integers
        if self.e.get().isdigit() == False:

            self.e.delete("BLANK", 'end')#I need to replace 0 with the last character of the string

        else:
            #print the string of integers
            print self.e.get()




test = Test()
Beera answered 7/7, 2012 at 2:26 Comment(3)
What if someone presses ctrl-V and pastes a longer string?Tedford
I guess i should find a way then to search the string and delete anything thats not a numberBeera
See A Validating Entry Widget, especially the IntegerEntry subclass.Tedford
K
7

You could also change the line above as well, to this:

    if not self.e.get().isdigit():
        #take the string currently in the widget, all the way up to the last character
        txt = self.e.get()[:-1]
        #clear the widget of text
        self.e.delete(0, tk.END)
        #insert the new string, sans the last character
        self.e.insert(0, txt)

or:

if not self.e.get().isdigit():
     #get the length of the string in the widget, and subtract one, and delete everything up to the end
     self.e.delete(len(self.e.get)-1, tk.END)

Good job putting up a working example for us to use, helped speed this along.

Karie answered 7/7, 2012 at 2:28 Comment(4)
I understand why -1 would work but for some reason it deletes the whole string. Any idea Why?Beera
Seems like tkinter takes -1 as the 'default' for anything, so you might have to get tricky with it. Instead of deleting it like you have now, you could take the string that is currently set up, take off the last character, then put it back into the widget. Take a look at the update answerKarie
@TankorSmash: I suggest you delete the part of your answer that is incorrect. It will only cause confusion in the future.Tedford
@StevenRumbalski got your backKarie
O
1

If you are doing data validation you should be using the built-in features of the entry widget, specifically the validatecommand and validate attributes.

For a description of how to these atributes it see this answer.

Ouellette answered 7/7, 2012 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.