Home > database >  save userinput in a second windows
save userinput in a second windows

Time:03-19

I have a problem with my code the user input is saved when I run the program instead of when the button is clicked I also tried to make a function that detects if entry1.get() == none don't save the input "input" but this did not work thanks for your help and time

my code:

#imports

#define the first tk window
window = Tk()
window.geometry("655x600")
window.title("")

icon = PhotoImage(file="data/icons/icon.png")
window.iconphoto(True,icon)
window.config(background="#2e3033")

#savefiles
savefile1 = open("data/userinput/data1.txt","w", encoding="utf-8")

#button  functions
def new_window1():
    global entry1
    window2 = Tk()
    window2.geometry("500x100 200 300")
    window2.config(background="#2e3033")
    window2.title("Edit Button 1")
    entry1 = Entry(window2,width=100, font= ("Arial",12))
    entry1.place(x=5,y=30)
    Button1 = Button(window2, text="save",command=lambda:[savefile1.write(entry1.get()),window2.destroy()])
    Button1.place(x=5,y=70)


#buttons
image1 = PhotoImage(file="images/streamdeximage1.png")
button1 = Button(window, text="hello" , command=new_window1 , image=image1)
button1.place(x=20,y=20)

window.mainloop()

CodePudding user response:

Even though ur code saves the data on button click of second window on my side, here are some changes

  • There should be only one root window, that's TK(), if you have more than one window, then use Toplevel()
  • Use a context manager for saving data in the file as you opened the file but never closed it
  • remove that global declaration of entry, that doesn't make any sense
  • Use file.flush() if you need to write data immediately by flushing the buffer
def save_data(data):
    with open("data.txt", "w", encoding="utf-8") as file:
        file.write(data)
        file.flush()


# button  functions
def new_window1():
    window2 = Toplevel()
    window2.geometry("500x100 200 300")
    window2.config(background="#2e3033")
    window2.title("Edit Button 1")
    entry1 = Entry(window2, width=100, font=("Arial", 12))
    entry1.place(x=5, y=30)
    button1 = Button(window2, text="save", command=lambda: [save_data(entry1.get()), window2.destroy()])
    button1.place(x=5, y=70)
  • Related