我想做一个小的文本编辑器。
这工作正常,但当列表框中的文件未被选中时,我出现了一个错误:
clicked = listbox.get(index[0])
IndexError: tuple index out of range
当我在空白区域中单击2或3次时,就会发生这种情况。
我怎样才能解决这个问题?
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()
打印listbox.get之前的索引(索引[0])
(1,)(2,)(0,)(1,)(我在那个文件夹中有3个文件)
当我收到错误it print()时,我如何修复它?谢谢
暂无答案!
目前还没有任何答案,快来回答吧!