1

I am trying to save data in a file through a Tkinter app. If the file already exists and is currently open by another application, I can, of course, not write on it but I would like to inform the user that the file is open somewhere else.

In Python Console (Spyder), I receive the following message:

Exception in Tkinter callback
[...]
  File "MyFile.py", line 200, in plot_data_save_file
    file=open(file_name,"w")
PermissionError: [Errno 13] Permission denied: "FileToSaveDataIn.xy"

I know how to create a Tkinter messagebox but how can I know if Python Console raised the error and pass this information to Tkinter?

3
  • 2
    Use a try statement. That can take an error and provide it to you for use in a messagebox. Commented Dec 7, 2022 at 17:35
  • I don't know yet how to use a try statement. What should I try? The function containing the saving process? Commented Dec 7, 2022 at 17:37
  • Duplicate is for the accepted answer, as it has nothing to do with tkinter. However if you want to handle exceptions after they're thrown from callbacks, in tkinter, see stackoverflow.com/questions/15246523/… and stackoverflow.com/questions/4770993/… Commented Dec 8, 2022 at 17:54

1 Answer 1

1

What you need is a try/except statement. This allows you to attempt some code and if it errors you can then capture that error and use it however you want. In this case I am printing it to console but you can simple use that same variable to load to a messagebox.

Here is a simple example of a try/except statement:

import tkinter.messagebox as box

try:
    # ... Some logic here ...

except BaseException as e:
    print('Exception: {}'.format(e))
    # This line should work for your needs
    # box.showerror('Error!', 'Exception: {}'.format(e))

Typically you would want to write specific handlers for errors instead of doing a general exception like I have done here but for illustrations reasons this will suffice.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.