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?

AlMa
  • 191
  • 8
  • 2
    Use a `try` statement. That can take an error and provide it to you for use in a messagebox. – Mike - SMT Dec 07 '22 at 17:35
  • I don't know yet how to use a `try` statement. What should I `try`? The function containing the saving process? – AlMa Dec 07 '22 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 https://stackoverflow.com/questions/15246523/handling-exception-in-python-tkinter and https://stackoverflow.com/questions/4770993/how-can-i-make-silent-exceptions-louder-in-tkinter – tevemadar Dec 08 '22 at 17:54

1 Answers1

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.

Mike - SMT
  • 14,784
  • 4
  • 35
  • 79