Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tkinter: Delete the Last Character of a String

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()
like image 263
Brandon Nadeau Avatar asked Jul 07 '12 02:07

Brandon Nadeau


People also ask

How do you remove the last character of a string in Python?

Using rstrip() to remove the last character The rstrip() is a built-in Python function that returns a String copy with trailing characters removed. For example, we can use the rstrip() function with negative indexing to remove the final character of the string.

What does end do in tkinter?

It doesn't "do" anything. It is a constant, the literal string "end". In this context it represents the point immediately after the last character entered by the user. The function get on a text widget requires two values: a starting position and an ending position.


2 Answers

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.

like image 26
Bryan Oakley Avatar answered Sep 25 '22 04:09

Bryan Oakley


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.

like image 82
TankorSmash Avatar answered Sep 24 '22 04:09

TankorSmash