[英]How to delete last character in text widget tkinter
I am attempting to make the following code work: It is meant to delete the last character of the text widget named _textBox (as a backspace on a keyboard would usually do)...我正在尝试使以下代码工作:它旨在删除名为 _textBox 的文本小部件的最后一个字符(作为键盘上的退格键通常会这样做)...
def addChar(_textBox, char):
global charCount
if charCount <= 15:
if char == "backSpace":
_textBox.delete(charCount, END)
if charCount != 0:
charCount = charCount - 1
else:
_textBox.insert(END, char)
charCount = charCount + 1
print(charCount)
It seems the only problem is the '.delete()' part of the code...似乎唯一的问题是代码的“.delete()”部分......
Does anybody know how i can use this properly to remove only the last character in the text widget?有人知道我如何正确使用它来仅删除文本小部件中的最后一个字符吗?
Thanks in advance:)提前致谢:)
To delete only the last character in an entry widget You can use the following code仅删除条目小部件中的最后一个字符您可以使用以下代码
entryname.delete(len(entryname.get())-1,END)
All Good Guys! 大家好!
I've followed Pat's Advice in rewriting the portion of code and it now works brilliantly! 我已经按照Pat的忠告重写了部分代码,现在它的运行非常出色! Here it is if anyone wants it: 如果有人需要,这里是:
def addChar(_textBox, char):
global charCount, strToInsert
if charCount == 0:
strToInsert = ""
if char == "backSpace":
strToInsert = strToInsert[:-1]
if charCount != 0:
charCount = charCount - 1
else:
if charCount <= 15:
strToInsert = strToInsert + char
charCount = charCount + 1
_textBox.delete("1.0", END)
_textBox.insert(END, strToInsert)
FYI: I do set the variable charCoun in another function... 仅供参考:我确实在另一个函数中设置了变量charCoun ...
To delete a character, you must give the index immediately before the character you want to delete (ie: to delete the very first character you would give it "1.0"
). 要删除一个字符,必须在要删除的字符之前立即给出索引(即:要删除第一个字符,您应该给它"1.0"
)。
The index END
represents the position just after invisible newline automatically added by tkinter. 索引END
代表tkinter自动添加的不可见换行符之后的位置。 "end-1" represents the position immediately before this newline. “ end-1”表示此换行符之前的位置。 Since you want to delete the last character that the user entered (which is before this newline), you must use "end-2c"
(end minus two characters). 由于要删除用户输入的最后一个字符(在此换行符之前),因此必须使用"end-2c"
(结尾减去两个字符)。
I build a simple project here:我在这里建立一个简单的项目:
from tkinter import *
import tkinter as tk
screen=Tk()
screen.title("Test")
def reponsive():
txt.grid()
def ins(text):
txt.delete('1.0', END)
txt.insert(INSERT,text)
txt.grid()
def delete():
text=txt.get("1.0",END)
text=text[:-2]
ins(text)
bt=Button(screen,command=delete,text="DEL").grid()
txt=Text(screen)
reponsive()
screen.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.