2

I am trying to clear the text box i typed already with a Button 'Clear'.But its not clearing the text once the button is clicked!

Please fix my problem!Answer will be appreciated!

import tkinter as tki

class App(object):

    def __init__(self,root):
        self.root = root
        txt_frm = tki.Frame(self.root, width=600, height=400)
        txt_frm.pack(fill="both", expand=True)
        # ensure a consistent GUI size
        txt_frm.grid_propagate(False)

        self.txt1 = tki.Text(txt_frm, borderwidth=3, relief="sunken", height=4,width=55)
        self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt1.grid(row=0, column=1, sticky="nsew", padx=2, pady=2)

        button1 = tki.Button(txt_frm,text="Clear", command = self.clearBox)
        button1.grid(column=2,row=0)
    def clearBox(self):
        self.txt1.delete(0, END)

root = tki.Tk()
app = App(root)
root.mainloop()
user3914506
  • 65
  • 1
  • 1
  • 6

1 Answers1

2

Since END is in tkinter you need to use tki.END or "end" (with quotes, lower case) also your starting index should be "1.0"(thanks to BryanOakley) instead of 0.

This one should work.

def clearBox(self):
    self.txt1.delete("1.0", "end")

EDIT: By the way it will be better if you use pack_propagate instead of grid_propagate since you used pack to place your frame.

EDIT2: About that index thing, it is written in here under lines and columns section.

...Line numbers start at 1, while column numbers start at 0...

Note that line/column indexes may look like floating point values, but it’s seldom possible to treat them as such (consider position 1.25 vs. 1.3, for example). I sometimes use 1.0 instead of “1.0” to save a few keystrokes when referring to the first character in the buffer, but that’s about it.

Community
  • 1
  • 1
Lafexlos
  • 7,618
  • 5
  • 38
  • 53
  • `0` and `0.0` are both invalid starting indexes. The first character in a text widget is `"1.0"` and the index should be a string, not a floating point number. – Bryan Oakley Aug 06 '14 at 15:08
  • @BryanOakley that is weird because 0.0 is working for me right now but if you say so, it is probably true. :D – Lafexlos Aug 06 '14 at 15:10
  • @Lafexlos: 0.0 works, but only because the developers were liberal in what they accept, and `0.0` gets translated to `"1.0"` internally. A proper index is a string of the form _line.column_, with lines starting at 1 and columns starting at zero. That's the documented format. – Bryan Oakley Aug 06 '14 at 16:21
  • 1
    @BryanOakley After you pointed out, I searched a bit and added those information as edit. Thanks for the heads up. – Lafexlos Aug 06 '14 at 16:35