Learning Tkinter

Doran, Harold HDoran at air.org
Wed Apr 16 14:46:13 CEST 2008

I am currently reading An Intro to Tkinter (1999) by F. Lundh. This doc
was published in 1999 and I wonder if there is a more recent version.
I've googled a bit and this version is the one I keep finding. I like
how this document is organized and also how it provides the code with
visuals of what should appear on the screen. If there are other docs I
should read, please let me know.

Second, I am trying to work through a couple of the examples and make
some small tweaks as I go to see how new things can work. In the first
case, I have copied the code in the book to see how the menu works and
are created as in the example menu.py below. I see how menus are created
and how the command option is used to call the function callback.

# menu.py
from Tkinter import *

def callback():
    print "called the callback!"

root = Tk()

# create a menu
menu = Menu(root)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=harold)
filemenu.add_command(label="Open...", command=callback)
filemenu.add_command(label="Exit", command=callback)

helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=callback)


However, I now want to incorporate a basic python program with a
command. Say I have a simple program called test.py 

# test.py
filename = raw_input("Please enter the file you want to open: ")
new_file = raw_input("Save the output file as: ")

f = open(new_file, 'w')
new = open(filename, 'r')

for line in new:
	x = line.split('\t')
	print >> f, x[0],':', x[1]     

To make this example complete assume I have a text file like this

# data.txt
1	one
2	two
3	three
4	four

So, the user currently just follows directions on the screen, enters the
file names, and I get what I want. I'd like to try experimenting with
gui programming to see if the python programs I have written can be made
even more user friendly. I currently use py2exe to create executables so
that others in my organization can use these programs. 
In that spirit, say I want to have a menu option that allows the user to
search their computer for this file, execute the python code and then
save the result as a user-defined filename. So, I guess my questions are
how do I associate the portion of code in menu.py
"filemenu.add_command(label="Open...", command=callback)" with an
operation that gives the user the ability to search the drives on their
machine and then once they do let python execute the code in test.py?

Many thanks,

More information about the Python-list mailing list