School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 306,761 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,648 people online right now. Registration is fast and FREE... Join Now!




Tkinter, Part 3 - Dialogs

 
Reply to this topicStart new topic

> Tkinter, Part 3 - Dialogs

Dogstopper
Group Icon



post 28 Oct, 2009 - 10:23 AM
Post #1


Tkinter Part 3 – tkFileDialog.

This tutorial will take you through tkFileDialog module where we make a very basic text editor which we will use for the next three tutorials.

Right, let's dive right in with the introductory code. The comments will explain much of it as we go.

CODE

#! /usr/bin/python

from Tkinter import *
import tkFileDialog

class App:

    def __init__(self):
        # Set up the screen, the title, and the size.
        self.root = Tk()
        self.root.title("Notpad")
        self.root.minsize(width=500,height=400)
              
        # Set up basic Menu
        menubar = Menu(self.root)

        # Set up a separate menu that is a child of the main menu
        filemenu = Menu(menubar,tearoff=0)
        filemenu.add_command(label="New File", command=self.doNew,
                             accelerator="Ctrl+N")

        # Try out openDialog
        filemenu.add_command(label="Open", command=self.doOpen,
                             accelerator="Ctrl+O")

        # Try out the saveAsDialog
        filemenu.add_command(label="Save", command=self.doSaveAs,
                             accelerator="Ctrl+Shift+S")
        menubar.add_cascade(label="File", menu=filemenu)
      
        self.root.config(menu=menubar)

        # Set up the text widget
        self.text = Text(self.root)
        self.text.pack(expand=YES, fill=BOTH) # Expand to fit
                                 # vertically and horizontally


This constructor does several things for us, primarily just getting a menu system set up and to set event handlers for them. Additionally, we set up a pre-prepared Text widget. It the constructor, expand tells the widget to fill the area around it and fill makes it expand in all directions.

The next thing that we must do is to set up the event handlers (this is still in the App class).


CODE

    def doNew(self):
        # Clear the text
        self.text.delete(0.0, END)


I think that this code segment is self-explanatory where it just clears the text from the text widget.
Next, we set up the save dialogs.

CODE

    def doSaveAs(self):
        # Returns the saved file
        file = tkFileDialog.asksaveasfile(mode='w')
        textoutput = self.text.get(0.0, END) # Gets all the text in the field
        file.write(textoutput.rstrip()) # With blank perameters, this cuts
                                          # off all whitespace after a line.
        file.write("\n") # Then we add a newline character.


You are probably wondering at this point why we destroy the white space and then adding a newline and not just letting it being added naturally. If it is not done in this manner, then the extra whitespace is added to the end of the current text. I think that this is a glitch in the Tkinter system, but this is one approach to fixing it.

Finally, the last handler loads text from a file into the Text widget.


CODE

    def doOpen(self):
        # Returns the opened file
        file = tkFileDialog.askopenfile(mode='r')
        fileContents = file.read() # Get all the text from file.

        # Set current text to file contents
        self.text.delete(0.0, END)
        self.text.insert(0.0, fileContents)


This code reads from a file and writes it to the text.
Here is the final piece of code for this program that initializes it.


CODE

app = App()
app.root.mainloop()


Now, those aren't the only functions in tkFileDialog, and here are the rest.
  • askopenfilename() returns just the filename and you must open it yourself.
  • askopenfilename() returns just the filename and you must open it yourself.
  • asksaveasfilename() is the same as the previous except you must save it yourself.
  • askdirectory() returns the directory.
  • askopenfilenames() returns the names of several files.
  • askopenfiles(mode='r') returns a list of several open files.


Finally, there are several options which can go in the parameter list.
  • -defaultextension “string”: sets the default extension to append to the filename
  • -filetypes: A list of tuples like so: [(“all files”, “.*”), (“Python files”, “.py”)]
  • -initialdir: The directory that initially pops up for file looking.
  • -initialfile: designates initial filename. *Note: This is not supported on Mac!
  • -multiple: Allows multiple files on open dialog. *Note: Not standard on Mac
  • -message: Specific message that appears on client *Note: Only available on Mac with Navigation services enabled
  • -parent: Makes the window given the parent of this dialog.
  • -title: Specifies a string as the title.

Thanks for reading! I hope you enjoyed it!
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/20/09 05:35PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month