Reputation: 83
Hi I am struggling with tkinter
. I simply want to delete the first character of a text widget, for example on button click. I have seen [Bryan Oakleys answer here][1] but unfortunately it does not work for me.
Like he said I tried it like this:
text.delete("1.0")
But like I said it does not work. I also do not get any error. It simply does not work.
from tkinter import *
import time
class TipManager:
def __init__(self):
self.root = Tk()
self.root.attributes("-fullscreen", True)
self.root.bind("<KeyPress>", self.click)
self.clicks = 0
self.chars = []
self.cps = 0
self.start = time.time()
self.average()
self.text = Text(self.root,tabs=2,font=("Arial", 30))
self.text.grid(row=0, column=0)
self.root.mainloop()
def click(self,e):
if e.char.isalpha() or e.char == " ":
self.chars.append(e.char)
self.clicks += 1
if len(self.chars) > 15:
self.text.delete("1.0")
self.text.configure(state="normal")
self.text.insert(END, e.char)
self.text.configure(state="disabled")
if e.char == "\x7f":
if not len(self.chars) == 0:
self.text.configure(state="normal")
self.text.delete("end-2c")
self.text.configure(state="disabled")
del self.chars[-1]
def average(self):
self.cps = self.clicks
print(f"Your average typing speed was {self.cps} c/s")
self.clicks = 0
self.root.after(1000, self.average)
tipp_10 = TipManager()
This is my full code [1]: https://stackoverflow.com/questions/49232866/how-to-delete-last-character-in-text-widget-tkinter#:~:text=The%20index%20END%20represents%20the,(end%20minus%20two%20characters).
Upvotes: 0
Views: 300
Reputation: 855
Be sure your text box is enabled before you insert/delete from it. So put self.text.configure(state="normal")
before this line:
if len(self.chars) > 15:
self.text.delete("1.0")
Upvotes: 0
Reputation: 7680
Change:
if len(self.chars) > 15:
self.text.delete("1.0")
self.text.configure(state="normal")
self.text.insert(END, e.char)
self.text.configure(state="disabled")
to:
self.text.configure(state="normal")
if len(self.chars) > 15:
self.text.delete("1.0")
self.text.insert(END, e.char)
self.text.configure(state="disabled")
The <tkinter.Text>
's state must be "normal"
when you .insert
/.delete
from it.
Upvotes: 2