Writing to a file will not work in def

My code will not append in def when called upon in a button. heres my code:

from tkinter import *
import tkinter.messagebox as mbox

win = Tk()
win.title('Login')
none=",   "
frame=Frame(win)
entry=Entry(frame)

def login():
    file = open('loginlogger.txt', 'a')
    file.write(entry.get())
    file.write(none)
    file.close()
    mbox.showinfo('Greet','Welcome '+entry.get())

btn=Button(frame,text='Enter name to login.',command=login)

btn.pack(side=RIGHT,padx=5)
entry.pack(side=LEFT)
frame.pack(padx=20,pady=20)

win.mainloop()

Hi,

I have updated your script with added functionality.

  1. Can now use the carriage return to enter input as opposed to just using the mouse.
  2. Auto focuses the pointer inside the entry box both at start-up and after every entry.
  3. It is not recommended to use the open-ended import of:
    from tkinter import * for two main reasons:
    a. tkinter names may clash with native names (user defined names)
    b. Easier to interpret your code (maybe another user) by noting which names are from import packages and which are user defined. Thus, it is best practice to prefix imported package names with library name or alias.
  4. Switched to using the with open file open statement. This method of opening a file always closes a file on exit automatically and thus is the preferred way of opening files. Other types require the pairing with an explicit close statement. If there is an exception, the ‘with open’ method will still close the file.
  5. Incorporating the pathlib library for defining the path and filename.
  6. Added code to clear the entry box after every write.

I have tested this script on my system and it is working fine.

import tkinter as tk
import tkinter.messagebox as mbox

from pathlib import Path
file_path = Path('/Users/your_pc_name_here/Desktop/tester.txt')

win = tk.Tk()
win.title('Login')
none = ",   "
frame = tk.Frame(win)
entry = tk.Entry(frame)

def login(*args):

    with open(file_path, 'a+', encoding='UTF-8') as file:

        file.write(entry.get())
        file.write(none)
        mbox.showinfo('Greet', 'Welcome ' + entry.get())
        entry.delete(0, tk.END)  # After writing to file, clears the entry box
        entry.focus_set()           # Refocuses cursor inside entry box after every write

btn = tk.Button(frame, text = 'Enter name to login.', command = login)
btn.bind("<Return>", login)  # This adds the carriage return functionality to button

btn.pack(side = tk.RIGHT, padx = 5)
entry.pack(side = tk.LEFT)
frame.pack(padx = 20, pady = 20)
entry.focus_set()       # Puts cursor inside entry at start-up

win.mainloop()

1 Like

Thanks for helping me out. I really appreciate it.

but it will still not write and also says

FileNotFoundError: [Errno 2] No such file or directory: ‘users\puter\desktop\login.txt’
Exception in Tkinter callback
Traceback (most recent call last):
File “c:\Users\silas\AppData\Local\Programs\Python\Python312\Lib\tkinter_init_.py”, line 1968, in call
return self.func(*args)
^^^^^^^^^^^^^^^^
File “C:\Users\silas\OneDrive\Desktop\login.py”, line 15, in login
with open(file_path, ‘a+’, encoding=‘UTF-8’) as file:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: ‘users\puter\desktop\login.txt’
PS C:\Users\silas\OneDrive\Desktop>

“users\puter\desktop\login.txt” is a relative path. It starts in the current directory, wherever that is, then down into a subfolder called “users”, further down into a subfolder called “puter”, further down into a subfolder called “desktop”, then to a file called “login.txt”.

The issue appears to be the fact that you are using backward slashes as opposed to forward slashes in the file path. Should have this form:

file_path = Path('/Users/your_pc_name_here/Uesktop/tester.txt')

instead of:

file_path = Path('\Users\your_pc_name_here\Desktop\tester.txt')

By the way, for the first item (1. ) added from the previous post, as soon as you enter the last character in the entry, then hit the Tab key then Enter.

If you want to use backward slashes, you will have to prefix the file path with the letter r as in:

file_path = Path(r'\Users\your_pc_name_here\Desktop\tester.txt')
1 Like

Neos_Helios, I’ve tried out your code and it seems to work just fine. I can see the text gets appended to the file. Are you seeing any error messages when you run your original code?

That’s actually not quite right as the concern you’re bringing up only affects string literals. You you pass it in like the original code sample does from a tkinter input then the path separator style doesn’t matter on Windows. I think the comment from @MRAB is correct.

Now instead of giving an error message, it just doesn’t write. No error message

Your code has this:

file = open('loginlogger.txt', 'a')

so it’s writing to a file called ‘loginlogger.txt’ that’s in the current working directory, but where is that?

Try adding this at the top:

import os
print('Current working directory is os.getcwd())

Is the file in that folder?

2 Likes

I think Matthew meant to write:

import os
print('Current working directory is', os.getcwd())
2 Likes

Oops! Correct! :slight_smile:

Hi Paul,

using filemode ‘a+’ is seldom useful. Reading and appending to a file is not clearly defined over different OSes. Since you are only writing, ‘a’ is sufficient. Keep your with-Block as small as possible.

def login(*args):

    with open(file_path, 'a', encoding='UTF-8') as file:
        file.write(entry.get() + none)
    mbox.showinfo('Greet', f'Welcome {entry.get()}')
    # After writing to file, clears the entry box
    entry.delete(0, tk.END)
    # Refocuses cursor inside entry box after every write 
    entry.focus_set()

If you want to write to your Desktop, use

file_path = Path.home() / 'Desktop/tester.txt'