[Tutor] to employ Tkinter

John Fouhy jfouhy at paradise.net.nz
Tue Mar 1 21:03:14 CET 2005


Andrzej Kolinski wrote:
> I would like to go even further and employ Tkinter to:
> - open and run a C and/or Python code (including arguments where 
> necessary),
> - name and save generated html/php files.
> 
> The only thing I found is the following line of code:
> filemenu.add_command(label="Open...", command=askopenfile)
> - which obviously does not do the job.

Tkinter is a GUI framework ... Basically, with Tkinter, you attach the 
code you want to run to GUI events.

eg:

from Tkinter import *
import tkMessageBox
import tkFileDialog
import os

# This will hold the entry widgets, for later reference.
entries = {}

tk = Tk()

Label(tk, text='Program:').grid(row=0, column=0)
entries['program'] = Entry(tk)
entries['program'].grid(row=0, column=1)

Label(tk, text='Arg 1:').grid(row=1, column=0)
entries['arg1'] = Entry(tk)
entries['arg1'].grid(row=1, column=1)

Label(tk, text='Arg 2:').grid(row=2, column=0)
entries['arg2'] = Entry(tk)
entries['arg2'].grid(row=2, column=1)

Label(tk, text='Arg 3:').grid(row=3, column=0)
entries['arg3'] = Entry(tk)
entries['arg3'].grid(row=3, column=1)

# Build a 'Browse' button for the program field.
def browseProg(self):
     prog = tkFileDialog.askopenfilename()
     if prog:
         entries['program'].delete(0, END)
         entries['program'].insert(END, prog)

Button(tk, text='Browse', command=browseProg).grid(row=0, column=2)

# Callback to run the program specified.
def runProgram():
     prog = entries['program'].get()
     arg1 = entries['arg1'].get()
     arg2 = entries['arg2'].get()
     arg3 = entries['arg3'].get()

     if not os.path.exists(prog):
         tkMessageBox.showerror('Error', '%s: File not found!' % prog)
         return

     args = filter(None, [arg1, arg2, arg3])

     os.system(' '.join([prog] + args))

Button(tk, text='Run', command=runProgram).grid()

tk.mainloop()

---------------------------------------------------------

It should go without saying that there are security concerns when you 
are allowing users to run arbitrary programs!

-- 
John.


More information about the Tutor mailing list