'My Tkinter Python code returns "I/O operation error"

I am trying to create a code that will detect cursor coordinates upon user's entry and exit of the Tkinter window. However, I am not getting an output the first three times I click on the window and then later I get "I/O operation error".

I tried:

from tkinter import *

root = Tk()
root.geometry("300x300")

text_entry = "You entered the window at: "
text_exit = "You exited the window at: "
file = "extension.txt"
open_file = open(file, "a")


def entry_exit(event):
    decide = open(file, "r")
    for line in decide:
        a = [].append(line)
    if a[0] == "Entry":
        print("Cursor entered at %d, %d".format(event.x, event.y))
    elif a[1] == "Exit":
        print("Cursor exited at %d, %d".format(event.x, event.y))


root.bind("<Enter>", lambda something: [open_file.write("Entry"), open_file.close(), entry_exit])
root.bind("<Leave>", lambda something_else: [open_file.write("Exit"), open_file.close(), entry_exit])

mainloop()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source