Johnnyyy
Johnnyyy

Reputation: 103

Unable to clear text in Tkinter

I'm developing a program that will read a text file and convert it into json format. When user clicked on "change data" it will deleted the previous data and change to new data. But the problem is whenever I clicked on "change data", the data will write into it without overwrite the previous keys. I tried with reviewjson.delete("1.0", END) but it seem like not working. My goal is to delete every previous keys and view current keys only.

Image

enter image description here

Sample Code

from tkinter import *
import json
from collections import OrderedDict


root = Tk()
root.title("Foghorn Publisher")
width = 1000
height = 680
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.minsize(1000, 900)
root.maxsize(1000, 900)


root.geometry("%dx%d+%d+%d" % (width, height, x, y))


file_data = OrderedDict()

global reviewjson
reviewjson = Text(root, bg='black', foreground="white")
reviewjson.place(x=1,y=1)
reviewjson.config(state=NORMAL)

List = ["abc","haha","fafafasf", "afasfasfasfa","asfasfasf"]
try:
    for content in List:
        file_data["data1"] = content[0:10]

        # output to JSON
        global tmp

        tmp = json.dumps(file_data, ensure_ascii=False, indent="\t") + "\n" + "\n"

        reviewjson.insert(END, tmp)

except:
    raise


def changedata():

        reviewjson.delete(1.0, "end")
        try:
            for content in List:
                file_data["data2"] = content[5:20]

                # output to JSON
                global tmp

                tmp = json.dumps(file_data, ensure_ascii=False, indent="\t") + "\n" + "\n"

                reviewjson.insert("end", tmp)

        except:
            raise

ChangeDataBtn = Button(root, text="change data", command=changedata, width=11)
ChangeDataBtn.place(x=300, y=400)

# ========================================Open Window==================================



# ========================================INITIALIZATION===================================
if __name__ == '__main__':

    root.mainloop()

Upvotes: 1

Views: 69

Answers (1)

CodingPeter
CodingPeter

Reputation: 241

The problem isn't directing at file_data.delete() or file_data.clear().

They are work without error, but file_data's value was given before:

file_data["data1"] = content[0:10] We need to clear it out.

So, you only need to change your changedata() function:

def changedata():   
    reviewjson.delete(1.0, "end")   
    file_data.clear()
    
    try:
        for content in List:
            file_data["data2"] = content[5:20]
            # output to JSON
            tmp = json.dumps(file_data, ensure_ascii=False, indent="\t") + "\n" + "\n"
            reviewjson.insert(1.0, tmp)
    except:
        raise

Upvotes: 1

Related Questions