Hello,

I am fairly new to Python. I have only skimmed the surface in an introductory class I just finished in college.

As my first program in Python, I am attempting to make a text editor.

I am wondering if there is a universal command to bring up a Save or Open file dialogue? Or should I continue creating Toplevel windows for Save and Open files?

If I create my own Save and Open windows, how do I get the user's computer directory structure to show up in a Listbox? And the files in that directory to show up in a Listbox?

Anyone have any insight on this?

Thank you for your help. Have a good one. -Dave

I assume you are using the Tkinter GUI toolkit. Using the tkFileDialog will make your life much easier, and brings up a dialog familiar to most users. Here is a short example ...

# a very simple Tkinter editor to show file read/write dialog
 
from Tkinter import *
from tkFileDialog import *
 
class App(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()
        self.text = Text()
        self.text.pack()
 
        menu = Menu(master)
        root.config(menu=menu)
        # file menu
        filemenu = Menu(menu, tearoff=0)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New")
        filemenu.add_command(label="Open", command=self.file_open)
        filemenu.add_command(label="Save", command=self.file_save)        
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.do_exit)
 
    def file_open(self):
        """open a file to read"""
        # optional initial directory (default is current directory)
        initial_dir = "C:\Temp"
        # the filetype mask (default is all files)
        mask = \
        [("Text and Python files","*.txt *.py *.pyw"), 
        ("HTML files","*.htm"), 
        ("All files","*.*")]        
        fin = askopenfile(initialdir=initial_dir, filetypes=mask, mode='r')
        text = fin.read()
        if text != None:
            self.text.delete(0.0, END)
            self.text.insert(END,text)
 
    def file_save(self):
        """get a filename and save the text in the editor widget"""
        # default extension is optional, here will add .txt if missing
        fout = asksaveasfile(mode='w', defaultextension=".txt")
        text2save = str(self.text.get(0.0,END))
        fout.write(text2save)
        fout.close()
 
    def do_exit(self):
        root.destroy()
 
root = Tk()
root.title("a very simple editor")
app = App(root)
root.mainloop()

Wow, thank you vega!

That's exactly the code I was hoping to find!

After the user opens or saves a file with tkFileDialog, how can I retrieve the filename they used?

Check the documentation for tkFileDialog with help(tkFileDialog) and help(tkFileDialog.askopenfile). That will tell you what the dialog accepts as parameters and returns as values.

Jeff

After the user opens or saves a file with tkFileDialog, how can I retrieve the filename they used?

If you are looking for a filename then you have to use another method ... filename = tkFileDialog.askopenfilename(filetypes=[("Text files","*.txt")])

Great. Thanks again. tkFileDialog does exactly what I needed.

with the askopenfilename function, I ask the user for the file name, then I just use Python's open function to open the file and insert to the Text widget. worked out quite nicely.

Next, I am creating a Find feature on the text editor. So far I am using the Text widget's .search to go through and look for similarities in entry.get() with a for loop. When it finds similarities, I would like it to highlight the similarities (with events?) How can this be done? So far it only prints exact match of the word it finds. I just need to define an event to select at this starting index, and this ending index, but i dont know the syntax.

Thanks again for all your help. -Dave

here's my Find code so far:

from Tkinter import *

class Find(object):
    def __init__(self):
        global text1
        self.top1 = Toplevel()
        self.top1.title("Find Text")

        self.entry1 = Entry(self.top1)
        self.entry1.pack()

        self.button1 = Button(self.top1,
                              text = "Find",
                              command = self.find_text)
        self.button1.pack()
        self.button2 = Button(self.top1,
                              text = "Cancel",
                              command = self.exitp)
        self.button2.pack()
    def exitp(self):
        self.top1.destroy()
    def find_text(self):
        global text1
        new_word = ""
        word = self.entry1.get()
        text = text1.search(word, 0.0, stopindex = END)
        for text in word:
            new_word = new_word + text
        length = len(new_word)
        flength = length - length
        print new_word[flength:length]

root = Tk()
root.title("Find")

text1 = Text(root)
text1.pack(fill = BOTH,
           expand = 1)

button1 = Button(root,
                 text = "find",
                 command = Find)
button1.pack()

root.mainloop()

See if this works for you:

from Tkinter import *

class Find(object):
    def __init__(self):
        #global text1  << Not needed since you aren't assigning text1.
        self.top1 = Toplevel()
        self.top1.title("Find Text")

        self.entry1 = Entry(self.top1)
        self.entry1.pack()

        self.button1 = Button(self.top1,
                              text = "Find",
                              command = self.find_text)
        self.button1.pack()
        self.button2 = Button(self.top1,
                              text = "Cancel",
                              command = self.exitp)
        self.button2.pack()
        self.tags = []
    def exitp(self):
        self.top1.destroy()
    def find_text(self):
        #global text1
        new_word = ""
        for tag in self.tags:                         # undo last find
            text1.tag_config(tag,background='white')
        word = self.entry1.get()
        if not word:       ## Needed for error checking
            return

        lines = text1.get('0.0',END).split('\n')
        self.tags = []  # save tags for undo later
        for i in range(len(lines)):   # Normally, 'for line in lines' --
                                      # but we need the index!
            if lines[i].startswith(word):
                text1.tag_add('t%d'%i,'%d.0'%(i+1),'%d.%d'%(i+1,len(word)))
                text1.tag_config('t%d'%i,background='blue')
                self.tags.append('t%d'%i)
        print self.tags  # just to see what's going on. comment this out
        
            
root = Tk()
root.title("Find")

text1 = Text(root)
text1.pack(fill = BOTH,
           expand = 1)

button1 = Button(root,
                 text = "find",
                 command = Find)
button1.pack()

root.mainloop()

Jeff

i want to know how to get the tag´s in text editor to save in (.doc)

def file_save(self):
        """get a filename and <strong class="highlight">save</strong> the text in the editor widget"""
        # default extension is optional, here will add .txt if missing
        fout = asksaveasfile(mode='w', defaultextension=".txt")
        text2save = str(self.text.get(0.0,END))
        fout.write(text2save)
        fout.close()

because when i save the text in (.doc) format dont show tag´s

I'm having trouble saving unicode characters to a .txt or a .doc file

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.