Page 1 of 1

Tkinter, Part 3 - Dialogs

#1 Dogstopper  Icon User is online

  • The Ninjaducky
  • member icon



Reputation: 2871
  • View blog
  • Posts: 11,026
  • Joined: 15-July 08

Posted 28 October 2009 - 11:23 AM

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.

#! /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).


	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.

	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.


	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.


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!

Is This A Good Question/Topic? 1
  • +

Page 1 of 1