PyEditor1.6

DragonMastur 3 Tallied Votes 314 Views Share

I made a little py editor because I didn't want to go to all the troble of installing an idle, but I didn't like notepad either. Here it is!

JasonHippy commented: A great start, definitely something that can be built upon! +9
import PyEditorErrors as errors
import os, sys

if sys.hexversion >= 0x030000F0:
    runningPython3 = True
else:
    runningPython3 = False
if runningPython3:
    import tkinter.filedialog as tk_FileDialog
    from tkinter import*
else:
    from Tkinter import*
    import tkFileDialog as tk_FileDialog

class PyEditor:
	def doNew(self):
		self.askRoot = Tk()
		self.askRoot.geometry("300x200")
		self.askRoot.minsize(width=300, height=200)
		self.askRoot.title("Create New File")
		
		self.askFileLabel = Label(self.askRoot, text="Enter the file name.")
		self.askFileName = Entry(self.askRoot)
		self.askFileNameDoneButton = Button(self.askRoot, text="Done", command=self.doFileNameDone)
		
		self.askFileLabel.pack()
		self.askFileName.pack()
		self.askFileNameDoneButton.pack()

	def doFileNameDone(self):
		if str(self.askFileName) != '':
			file = open((self.currentDir+"/Programs/"+self.askFileName.get()), "a")
			self.filename = file.name
			file.close()
			self.windowText.delete(0.0, END)
			self.windowText.insert(0.0, "#")
			self.windowText.insert(END, self.filename)
			self.askRoot.destroy()
		else:
			errors.nothingError("Nothing Entered")
			self.askRoot.destroy()

	def doSave(self):
		if self.filename != "":
			file = open(self.filename, "w")
			currentContents = self.windowText.get(0.0, END)
			file.write(currentContents)
			file.close()
		else:
			errors.noFileError("File Not Found")
	
	def doOpen(self):
		file = tk_FileDialog.askopenfile(mode='r', title="Open File", defaultextension=".py", initialdir=self.currentDir+"/Programs/")
		if file != None:
			filecontents = file.read()
			self.windowText.delete(0.0, END)
			self.windowText.insert(END, filecontents)
			self.filename = file.name
			file.close()
		else:
			print("Nothing found. Command cancled.")

	def doRun(self):
		file = tk_FileDialog.askopenfile(mode='r', title="Run File", defaultextension=".py", initialdir=self.currentDir+"/Programs/")
		print("\nRunning",file.name+".\n")
		os.system('c:\\Python34\\python "'+file.name+'"')

	def doRunCurrent(self):
		if self.filename != "":
			print("\nRunning",self.filename+".\n")
			os.system('c:\\Python34\\python "'+self.filename+'"')
		else:
			errors.noFileError("File Not Found")

	def __init__(self):
		if sys.platform.startswith("darwin"):
			osType = "Mac"
		else:
			osType = "Other"
		
		self.filename = ""
		self.currentDir = os.getcwd()
		self.root = Tk()
		self.root.geometry("700x550")
		self.root.minsize(width=700, height=550)
		self.root.title("PyEditor 1.6")
		
		self.windowText = Text(self.root, width=200, height=150)
		self.windowText.pack()

		menubar = Menu(self.root, tearoff=0)

		filemenu = Menu(menubar, tearoff=0)
		runmenu = Menu(menubar, tearoff=0)

		if osType == "Other":
			filemenu.add_command(label="New", command=self.doNew, accelerator="Ctrl+N")
			filemenu.add_command(label="Save", command=self.doSave, accelerator="Ctrl+S")
			filemenu.add_command(label="Open", command=self.doOpen, accelerator="Ctrl+O")
			filemenu.add_separator()
			filemenu.add_command(label="Exit", command=self.root.destroy, accelerator="Ctrl+E")

			runmenu.add_command(label="Run", command=self.doRun, accelerator="Ctrl+R")
			runmenu.add_command(label="Run Current", command=self.doRunCurrent, accelerator="Ctrl+Shift+R")
		elif osType == "Mac":
			filemenu.add_command(label="New", command=self.doNew, accelerator="Command+N")
			filemenu.add_command(label="Save", command=self.doSave, accelerator="Command+S")
			filemenu.add_command(label="Open", command=self.doOpen, accelerator="Command+O")
			filemenu.add_separator()
			filemenu.add_command(label="Exit", command=self.root.destroy, accelerator="Command+E")

			runmenu.add_command(label="Run Program", command=self.doRun, accelerator="Command+R")
			runmenu.add_command(label="Run Current", command=self.doRunCurrent, accelerator="Command+Shift+R")
		
		menubar.add_cascade(menu=filemenu, label="File")
		menubar.add_cascade(menu=runmenu, label="Run")

		self.root.config(menu=menubar)
		self.windowText.insert(END, "Select a menu or click help to start.")


if __name__ == "__main__":
	app = PyEditor()
	app.root.mainloop()
JasonHippy 739 Practically a Master Poster

It's a nice start I suppose. There are a few bugs and other improvements that could be made here and there, to make it a bit more robust and more cross-platform.

For starters, the biggest problem:
You haven't included the listing for your PyEditorErrors module. That's a bit of a deal-breaker right there!

But commenting out that import statement should allow your program to run - at least until we hit a line which tries to call a function in the errors module! :) Commenting out those calls should fix that too (in leiu of the actual listing of that module).

The other bugs/problems I spotted stem from using hard-coded paths in your program.

For example: Trying to create a new file will fail if the user doesn't have a sub-directory called 'Programs' in the current working directory, where the user is running your editor from.

Ideally, the user should be able to choose where to save their new file to, rather than it going to a hard-coded location that might not even exist on the users machine.

Also, you have some code in your program to set up alternative keyboard shortcuts for mac based OSes. But in your 'run' functionality, you are using hard-coded, windows-only paths to the python3.4 executable.

So what if the user is using a different version of python (2.6, 2.7, 3.2)? Or Python is installed elsewhere? Or they are using a different OS (Linux, Mac, BSD)?

Sure, the user could edit your script to replace those hard-coded paths with something compatible with their system. But ideally, your program should be able to detect which os is in use. It should then be able to use that information to perform platform specific actions in a manner that is compatible with the OS currently in use.

Also, in the import section, you do some conditional importing based on whether we are running python2 or python3. But again, your 'run' functionality is hard-coded to run the script using python3.4. Again, if we are running your editor using python2, then surely python2 should be used to run the users script?!

As I said, it's a great start for a minimalist python editor/mini-IDE. And because of the inclusion of the Mac-style keyboard shortcuts, you have obviously thought about users running other OSes. The hard-coded, Windows-only paths kinda negate that effort a little bit, but you certainly have something that can be built upon!

DragonMastur 23 Light Poster

I have another version coming, 1.6.2, it has more improvements. I comment things out mostly because I try to make them work in the future. It is also cross platform.

DragonMastur 23 Light Poster

I got it wrong I have v1.6.3, not v1.6.2. But either way here it is. Almost double in length.

#/User/bin/Python
import os, sys

if sys.hexversion >= 0x030000F0:
    runningPython3 = True
else:
    runningPython3 = False
if runningPython3:
    import tkinter.filedialog as tk_FileDialog
    from tkinter import*
else:
    from Tkinter import*
    import tkFileDialog as tk_FileDialog

class PyEditorErrors:
    def nothingError(self, title="nothingError", buttonText="OK"):
        nothingErrorRoot = Tk()
        nothingErrorRoot.geometry("300x100")
        nothingErrorRoot.minsize(width=300, height=100)
        nothingErrorRoot.title(title)

        nothingErrorMsg = Label(nothingErrorRoot, text="Nothing entered please try again.")
        nothingErrorButton = Button(nothingErrorRoot, text=buttonText, command=nothingErrorRoot.destroy)
        nothingErrorMsg.pack()
        nothingErrorButton.pack()

    def noFileError(self, title="noFileError", buttonText="OK"):
        noFileErrorRoot = Tk()
        noFileErrorRoot.geometry("300x100")
        noFileErrorRoot.minsize(width=300, height=100)
        noFileErrorRoot.title(title)

        noFileErrorMsg = Label(noFileErrorRoot, text="No file found try opening more files.")
        noFileErrorButton = Button(noFileErrorRoot, text=buttonText, command=noFileErrorRoot.destroy)
        noFileErrorMsg.pack()
        noFileErrorButton.pack()

    def mendList(self, list):
        returnstr = ""
        for things in list:
            returnstr += str(things) + "\ "
        return str(returnstr)

    def mendStr(self, str):
        varlist = [str.split(" ")]
        mendList(varlist)

class PyEditor:
    def doNew(self):
        self.askRoot = Tk()
        self.askRoot.geometry("300x200")
        self.askRoot.minsize(width=300, height=200)
        self.askRoot.title("Create New File")

        self.askFileLabel = Label(self.askRoot, text="Enter the file name.")
        self.askFileName = Entry(self.askRoot)
        self.askFileNameDoneButton = Button(self.askRoot, text="Done", command=self.doFileNameDone)

        self.askFileLabel.pack()
        self.askFileName.pack()
        self.askFileNameDoneButton.pack()

    def doFileNameDone(self):
        if str(self.askFileName.get()) != "":
            file = open((self.currentDir+"/Programs/"+self.askFileName.get()), "a")
            self.filename = file.name
            file.close()
            self.windowText.delete(0.0, END)
            self.windowText.insert(0.0, "#")
            self.windowText.insert(END, self.filename)
            self.askRoot.destroy()
        else:
            #self.errors.nothingError("Nothing Entered")
            print("Nothing Entered. Could not create new file.")
            self.askRoot.destroy()

    def doSave(self):
        if self.filename != "":
            file = open(self.filename, "w")
            currentContents = self.windowText.get(0.0, END)
            file.write(currentContents)
            file.close()
            print("Saved contents to",self.filename)
        else:
            #self.errors.noFileError("File Not Found")
            print("File not found. File might not exist.")

    def doSaveAs(self):
        file = tk_FileDialog.asksaveasfile(mode='w', title="Save As File", defaultextension=".py", initialdir=self.currentDir+"/Programs/")
        textoutput = self.windowText.get(0.0,END)
        if file != None:
            file.write(textoutput.rstrip())
            file.write('\n')
            self.filename = file.name
            print("Saved contents to",self.filename)
        else:
            print("Nothing found. Cannot save file.")

    def doOpen(self):
        file = tk_FileDialog.askopenfile(mode='r', title="Open File", defaultextension=".py", initialdir=self.currentDir+"/Programs/")
        if file != None:
            filecontents = file.read()
            self.windowText.delete(0.0, END)
            self.windowText.insert(END, filecontents)
            self.filename = file.name
            file.close()
            print("Opened",self.filename)
        else:
            print("Nothing found. Command cancled.")

    def doRun(self):
        file = tk_FileDialog.askopenfile(mode='r', title="Run File", defaultextension=".py", initialdir=self.currentDir+"/Programs/")
        if file != None:
            print("\nRunning",file.name+".\n")
            if osType == "Other":
                os.system('c:\\Python34\\python "'+file.name+'"')
            else:
                os.system("python "+file.name)
        else:
            print("\nUnable to run. No file selected\n")

    def doRunCurrent(self):
        if self.filename != "":
            print("\nRunning",self.filename+".\n")
            if osType == "Other":
                os.system('c:\\Python34\\python "'+file.name+'"')
            else:
                os.system("python "+file.name)
        else:
            #self.errors.noFileError("File Not Found")
            print("File not found. Please open more files.")

    def findIt(self):
        if self.findEntry.get() != "":
            self.Find(self.findEntry.get())
        else:
            print("Nothing entered operation cancled.")
        self.findRoot.destroy()

        # Finder off. Not working. 
    def doFind(self):
        self.findRoot = Tk()
        self.findRoot.geometry("300x200")
        self.findRoot.title("Find")
        self.findRoot.minsize(width=300, height=200)

        self.findEntryLabel = Label(self.findRoot, text="Type in key word to find.")
        self.findEntry = Entry(self.findRoot)
        self.findEntryGo = Button(self.findRoot, text="Find", command=self.findIt)
        self.findEntryLabel.grid(row=0)
        self.findEntryGo.grid(row=1, column=0, padx=10)
        self.findEntry.grid(row=1, column=1, columnspan=7)

    def Find(self, msg):
        filelen = len(self.windowText.get(0.0, END))
        for x in range(0, filelen):
            x = float("0."+str(x))
            finder = self.windowText.search(msg, x)
            if finder != "":
                filemsg = self.windowText.get(x+0.1, finder)
                self.windowText.delete(x+0.1, finder)
                self.windowText.insert(x+0.1, filemsg, "FinderWrite")

    def __init__(self):
        self.errors = PyEditorErrors()
        if sys.platform.startswith("darwin"):
            osType = "Mac"
        else:
            osType = "Other"

        self.filename = ""
        self.currentDir = os.getcwd()
        self.root = Tk()
        self.root.geometry("700x550")
        self.root.minsize(width=700, height=550)
        self.root.title("PyEditor 1.6.3")

        self.windowTextScrollY = Scrollbar(self.root, orient=VERTICAL)
        self.root.option_add("*Text.Font", "helvetica 10")
        self.windowText = Text(self.root, width=200, height=150, undo=TRUE)
        self.windowText.pack(side="left", fill="both", expand=True)
        self.windowTextScrollY.config(command=self.windowText.yview)
        self.windowTextScrollY.pack(side=RIGHT,fill=Y)


        menubar = Menu(self.root, tearoff=0)

        filemenu = Menu(menubar, tearoff=0)
        editmenu = Menu(menubar, tearoff=0)
        runmenu = Menu(menubar, tearoff=0)
        findmenu = Menu(menubar, tearoff=0)

        if osType == "Other":
            filemenu.add_command(label="New", command=self.doNew, accelerator="Ctrl+N")
            filemenu.add_command(label="Save", command=self.doSave, accelerator="Ctrl+S")
            filemenu.add_command(label="Save As", command=self.doSaveAs, accelerator="Ctrl+Shift+S")
            filemenu.add_command(label="Open", command=self.doOpen, accelerator="Ctrl+O")
            filemenu.add_separator()
            filemenu.add_command(label="Exit", command=self.root.destroy, accelerator="Ctrl+E")

            editmenu.add_command(label="Undo", command=self.windowText.edit_undo, accelerator="Ctrl+Z")

            runmenu.add_command(label="Run Program", command=self.doRun, accelerator="Ctrl+R")
            runmenu.add_command(label="Run Current", command=self.doRunCurrent, accelerator="Ctrl+Shift+R")

            #findmenu.add_command(label="Find", command=self.doFind, accelerator="Ctrl+F")
        elif osType == "Mac":
            filemenu.add_command(label="New", command=self.doNew, accelerator="Command+N")
            filemenu.add_command(label="Save", command=self.doSave, accelerator="Command+S")
            filemenu.add_command(label="Save As", command=self.doSaveAs, accelerator="Command+Shift+S")
            filemenu.add_command(label="Open", command=self.doOpen, accelerator="Command+O")
            filemenu.add_separator()
            filemenu.add_command(label="Exit", command=self.root.destroy, accelerator="Command+E")

            editmenu.add_command(label="Undo", command=self.windowText.edit_undo, accelerator="Command+Z")

            runmenu.add_command(label="Run Program", command=self.doRun, accelerator="Command+R")
            runmenu.add_command(label="Run Current", command=self.doRunCurrent, accelerator="Command+Shift+R")

        menubar.add_cascade(menu=filemenu, label="File")
        menubar.add_cascade(menu=editmenu, label="Edit")
        menubar.add_cascade(menu=runmenu, label="Run")
        menubar.add_cascade(menu=findmenu, label="Find")

        self.root.config(menu=menubar)
        self.windowText.tag_config("BoldWrite", font=("Helvetica", "10", "bold"))
        self.windowText.tag_config("FindWrite", font=("Helvetica", "11", ), foreground="blue")
        self.windowText.insert(END, "Select a menu or click help to start.", "BoldWrite")


if __name__ == "__main__":
    app = PyEditor()
    app.root.mainloop()
    print("Good bey. See you soon!")
DragonMastur 23 Light Poster

Also check out my other program(s):

www.prestonprograming.weebly.com

And:

https://www.daniweb.com/software-development/python/code/497789/calculator

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.