0

I'm trying to make a small text editor.

This is working fine but I'm having an error when the file in the list box gets unselected:

clicked = listbox.get(index[0])
IndexError: tuple index out of range

This happens when I click 2 or 3 times in an empty area.

How can I fix this?

import os
import tkinter as tk
from tkinter import END, INSERT
from tkinter.filedialog import askopenfilename, asksaveasfilename
from tkinter.ttk import Combobox
import easygui as easygui

window = tk.Tk()
window.title("Text Editor")

pathtofiles="notas/"

def open_file(event):
    listbox = event.widget
    index = listbox.curselection()
    clicked = listbox.get(index[0])
    if clicked:
        name_file.delete('1.0', END)
        name_file.insert(INSERT, clicked)
        txt_edit.delete('1.0', END)
        f = open(pathtofiles + clicked, "r")
        for x in f:
            txt_edit.insert(INSERT, x)


def create_txt():
    ficheiro = easygui.enterbox("Name your file?")
    if ficheiro:
        if ".txt" not in ficheiro:
            filename=ficheiro+".txt"
        txt_edit.delete('1.0', END)
        with open(pathtofiles + filename, "w+") as output_file:
            text = txt_edit.get(1.0, tk.END)
            output_file.write(text)
            name_file.delete('1.0', END)
            name_file.insert(INSERT, filename)
    return filename


def save_file():
    clicked = listbox.get(listbox.curselection())
    if clicked:
        clicked=listbox.get(listbox.curselection())
        with open(pathtofiles + str(clicked), "w") as output_file:
            text = txt_edit.get(1.0, tk.END)
            output_file.write(text)

txt_edit = tk.Text(window)
fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2, highlightbackground="black",  highlightthickness=0)

fr_buttons.grid(row=0, column=0, sticky="ns")
txt_edit.grid(row=0, column=1, sticky="nsew")

name_file = tk.Text(fr_buttons, height=1, width=15, relief="groove", borderwidth=2)
name_file.grid(row=0, column=0, pady=2)

listbox = tk.Listbox(fr_buttons)
listbox.grid(row=0, column=0,columnspan=2, pady=2, sticky="w")
listbox.bind('<<ListboxSelect>>', open_file)

btn_novo = tk.Button(fr_buttons, width="5",text="New", bg='red',fg='blue', command=create_txt)
btn_novo.grid(row=1, column=0, sticky="nw", padx=5)

btn_save = tk.Button(fr_buttons, width="5",text="Save", bg='red',fg='red', command=save_file)
btn_save.grid(row=1, column=1, sticky="nw", padx=5)

files = os.listdir(pathtofiles)
for line in files:
    listbox.insert('end', line)


def autosave():
    pass
    #save_file()
    #window.after(1000, autosave)

autosave()
window.mainloop()

print the index before the listbox.get(index[0])

(1,) (2,) (0,) (1,) (i have 3 files in that folder)

when i get the error it print (), how can i fix this? thanks

i manage with this

def open_file(event):
try:
    listbox = event.widget
    index = listbox.curselection()
    print(index)
    clicked = listbox.get(index[0])
    if len(listbox.get(index[0])) > 1:
        name_file.delete('1.0', END)
        name_file.insert(INSERT, clicked)
        txt_edit.delete('1.0', END)
        f = open(pathtofiles + clicked, "r")
        log_error=""
        for x in f:
            txt_edit.insert(INSERT, x)
except Exception as e:
    MsgBox = messagebox.showerror("ERRO!!!!", "Please select a file!!!!!!111111111")
    log_error = "check"

now i dont get error but i still lose "focus" of the file selected and lose all changes.

newbPyth
  • 31
  • 9
  • You should only ask one question per post. I've removed the second question as it was unrelated to the first one. You can create a separate post to ask it again. – mkrieger1 Jul 27 '21 at 13:52
  • What is the console output if you add `print(index)` before the line with `listbox.get(index[0])` that throws an error? – mkrieger1 Jul 27 '21 at 13:53
  • (1,) (2,) (0,) (1,) when the error occours it print () – newbPyth Jul 27 '21 at 14:10
  • 1
    So the question is why `listbox.curselection()` returns an empty tuple, or if it is expected that it returns an empty tuple, you need to handle that case separately. – mkrieger1 Jul 27 '21 at 14:17
  • yes, thats the question, how can i handle when it returns an empty tuple? – newbPyth Jul 27 '21 at 15:06
  • See https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty – mkrieger1 Jul 27 '21 at 15:27
  • please see my update to the question. – newbPyth Jul 27 '21 at 15:37
  • "yes, thats the question, how can i handle when it returns an empty tuple?" Well, do you know what should happen if it returns an empty tuple? (Hint: *why* does it return an empty tuple?) Do you know how to check if it returns an empty tuple, and conditionally do something different? (Hint: what is `if` used for?) What is the actual difficulty? – Karl Knechtel Jul 27 '21 at 15:41
  • it happens because the listbox loses "focus" on the selected file when i start typing int the text – newbPyth Jul 27 '21 at 15:57

2 Answers2

0

fixed with a diferent call from listbox

 def onselect(event, listbox):
        w = event.widget
        try:
            idx = int(w.curselection()[0])
        except IndexError:
            return
        global clicked
        clicked=(w.get(idx))
        open_file(clicked)
        return clicked

listbox.bind('<<ListboxSelect>>', lambda e: onselect(e, listbox))

thank you all :)

newbPyth
  • 31
  • 9
-1

I tried to fix your problem by adding a message in the text box,

try:
    clicked = listbox.get(index[0])
except:
    txt_edit.insert(INSERT, 'File not found Please try again...\n')
    clicked = False

added clicked = False so that it won't run the if statements below

Vignesh
  • 1,553
  • 1
  • 10
  • 25
  • thanks, the problem was not the error, the problem is it skipping the filename when i select text in other text box – newbPyth Jul 27 '21 at 17:02
  • can you point me where you are clicking? because whereever i click i am not getting any error – Vignesh Jul 28 '21 at 06:40