My code currently functions as follows:
create directory --> change working directory to created directory --> option to generate .txt files into directory, viewable in a listbox --> select a .txt file from listbox and view contents in a text widget.
What I am struggling with is then finding a way to enter text and save / append to the currently open/viewed text file in the text widget.
code:
from tkinter import *
from os import mkdir, getcwd, path, listdir, chdir
def dir_gen():
curr_dir = getcwd()
print("curr dir", curr_dir)
fin_dir = path.join(curr_dir, r'note_folder')
print("fin dir", fin_dir)
if not path.exists(fin_dir):
makedirs(fin_dir)
print("directory created")
dir_gen()
flist = listdir("note_folder")
print("flist", flist)
chdir("note_folder")
def main_gui():
window = Tk()
window. geometry("400x400")
window.config(bg="#000000")
def go_home():
window.destroy()
main_gui()
print("refreshed window")
lbox = Listbox(window)
lbox.place(x=20, y=20)
listdir()
print("listdir", listdir())
for l in listdir():
lbox.insert(END, l)
add_note_entry = Entry(window)
add_note_entry.place(x=20, y=190)
add_note_entry.config(width=20)
add_line_entry = Entry(window)
add_line_entry.place(x=200, y=300)
add_line_entry.config(width=27)
def add_note():
title = add_note_entry.get()
hdl = open(title ".txt", "w")
hdl.close(), go_home()
def open_note(event):
x = lbox.curselection()[0]
print("x", x)
file = lbox.get(x)
print("file", file)
with open(file, 'r ') as file:
file = file.read()
text_output.delete('1.0', END)
text_output.insert(END, file)
def save_note():
pass
add_note_button = Button(window, command=add_note)
add_note_button.place(x=40, y=210)
add_note_button.config(width=10, height=2, text=("ADD NOTE"))
save_note_button = Button(window, command=save_note)
save_note_button.place(x=240, y=345)
save_note_button.config(width=10, height=2, text=("SAVE NOTE"))
text_output = Text(window)
text_output.place(x=200, y=20)
text_output.config(height=15, width=20)
lbox.bind("<<ListboxSelect>>", open_note)
window.mainloop()
main_gui()
I have tried
def save_note(event):
line = add_line_entry.get()
x = lbox.curselection()[0]
file = lbox.get(x)
file = str(filename)
print("file2", file)
with open(file, 'a') as file:
file.write(line)
open_note()
and
def save_note():
x = lbox.curselection()[0]
file = lbox.get(x)
hdl = open(file, 'r ')
nt = text_output.get(1)
for l in nt:
hdl.write(l)
hdl.close()
as the main ways to get this functioning, unable to adjust either to get them running.
CodePudding user response:
In the second function, tkinter does not expect the text widget get function to be indexed with an integer. Here I have recreated the second save function but edited the line nt = text_output.get(1) to nt = text_output.get('1.0', 'end'). This gets everything from the first to last character in a tkinter text widget.
def save_note():
x = lbox.curselection()[0]
file = lbox.get(x)
hdl = open(file, 'r ')
nt = text_output.get('1.0', 'end')
for l in nt:
hdl.write(l)
hdl.close()
