-1

sorry if this a dumb question... but I'm new to learning Python and this is a homework question...

So I want to stop people from reopening an already loaded file using tkinter - and have an error dialog box pop up when they try to open the file.

So far I've got this:

from tkinter import filedialog
from tkinter import messagebox

def open_file(self):
    openfiles=[]
    filename = filedialog.askopenfilename(filetypes=[("allfiles","*.txt")])

    if filename not in openfiles:
        openfiles.append(filename)
        self._filename = filename
        functiontoloadfile(filename)

    else:
        messagebox.showerror(filename + "is already open")

2 Answers2

1

Assuming open_files() is a function not inside of a class, you can persist your openfiles list like so:

openfiles=[]
def open_file(self):
    filename = filedialog.askopenfilename(filetypes=[("allfiles","*.txt")])

    if filename not in openfiles:
        openfiles.append(filename)
        functiontoloadfile(filename)
    else:
        messagebox.showerror(filename + "is already open")

This will keep your openfiles list across multiple invocations of the open_file function. Of course, you will need to make sure you remove from that list when the file is closed which can become a bit oh a headache.

An even better approach might be one, where you detect which UI elements are displaying the file, and infer from the presence of those UI elements whether or not the file is open.

Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
0

In python if you try opening a file that is already open you can raise an error like this:

try:
    myfile = open("myfile.csv", "r+") # or "a+", whatever you need
except IOError:
    print "Is already open"
Burkely91
  • 902
  • 9
  • 28