import sys import os from Tkinter import * import tkFileDialog import subprocess import platform def setPixel(image, pos, color): r,g,b = [color]*3 x,y = pos image.put("#%02x%02x%02x" % (r,g,b), (x, y)) def manualLoadFile(filename): global fileOpen global img f = open(filename, 'r') data1 = f.readlines() # remove comments, newlines, and blank lines data = [x[:-1] for x in data1 if (x[0] != '#' and x != '\n')] if data[0] != "P2": print "Error: Incorrect Magic Number" return size = data[1].split() maxVal = int(data[2]) # remove the magic number, size, maxVal from data array del data[0] del data[0] del data[0] img = PhotoImage(width = int(size[0]), height = int(size[1])) num = 0 curPos = [0,0] for i in data: line = i.split() for j in line: setPixel(img, curPos, int(float(j) / float(maxVal) * 255)) num += 1 curPos[0] += 1 if curPos[0] >= int(size[0]): curPos[0] = 0 curPos[1] += 1 imageLabel.configure(image = img) imageLabel.image = img fileOpen = True return True def loadFile(filename): global fileOpen global img try: # to load as a binary pgm file img = PhotoImage(file=filename) imageLabel.configure(image = img) imageLabel.image = img fileOpen = True except Exception, e: # try to load it with our function for ascii pgm file! if manualLoadFile(filename): pass # all good else: print "Cannot Open File" imageLabel.pack(fill=BOTH,expand=1) def newWindow(filename): subprocess.Popen(["python", sys.argv[0], filename], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) def pickFiles(): global fileOpen filename = tkFileDialog.askopenfilename(multiple=1) if filename == "": return if os.name == 'nt': if platform.release() == 'XP': #If windows, handle files differently #THIS IS WINDOWS XP filename = filename[1:-1] # Strip the begining and end brackets filename = filename.split("} {") #split it into an array if platform.release() == '7' or platform.release() == 'Vista': #If windows, handle files differently #THIS IS WINDOWS 7 (AND PROBABLY VISTA) if filename.count("{") != 0: filename = filename[1:-1] # Strip the begining and end brackets filename = filename.split("} {") #split it into an array else: filename = [filename] print filename if not fileOpen: loadFile(filename[0]) for i in filename[1:]: newWindow(i) else: for i in filename: newWindow(i) # main routine starts here after our functions are defined root = Tk() root.wm_title("DisplayPGM") location = sys.argv[0] f = Canvas(root, width = 500, height = 500) f.pack() imageLabel = Label(f) img = None fileOpen = False menubar = Menu(root,tearoff= 0) m = Menu(menubar) menubar.add_cascade(label="File", menu=m) m.add_command(label="Open", command = pickFiles) m.add_command(label="Exit", command = root.quit) root.config(menu = menubar) if len(sys.argv) > 1: loadFile(sys.argv[1]) root.mainloop()