Python Tkinter:删除字符串的最后一个字符

时间:2012-07-07 02:26:08

标签: python tkinter tkinter-entry

我正在创建一个只允许输入数字的条目。如果该字符不是整数,我目前仍然在删除刚刚输入的字符。如果有人将“BLANK”替换为需要的内容,那将会有很多帮助。

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()

2 个答案:

答案 0 :(得分:5)

您也可以将上面的行更改为:

    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)

或:

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)

为我们提供一个可靠的工作示例,帮助加快了这一步。

答案 1 :(得分:1)

如果您正在进行数据验证,则应使用条目小部件的内置功能,特别是validatecommandvalidate属性。

有关如何使用这些属性的说明,请参阅this answer