user3914506
user3914506

Reputation: 65

python clearing text box with button event

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

Upvotes: 2

Views: 10705

Answers (1)

Lafexlos
Lafexlos

Reputation: 7735

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.

Upvotes: 2

Related Questions