* tkintermodule.c
	 (PyInit_tkinter): Only create stdin file handler when stdin
	 is a tty.
	 (Tkinter_Cleanup): New function.  This is an exit handler that
	 cleanup Tk.
diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c
index 31d127f..1653408 100644
--- a/Modules/_tkinter.c
+++ b/Modules/_tkinter.c
@@ -33,7 +33,11 @@
 #include <tk.h>
 
 extern char *getprogramname ();
+extern int isatty (int);
+
+/* Internal declarations from tkInt.h.  */ 
 extern int tk_NumMainWindows;
+extern struct { Tk_Window win; } *tkMainWindowList;
 
 /**** Tkapp Object Declaration ****/
 
@@ -58,6 +62,7 @@
 /**** Error Handling ****/
 
 static PyObject *Tkinter_TclError;
+static int quitMainLoop = 0;
 static int errorInCmd = 0;
 static PyObject *excInCmd;
 static PyObject *valInCmd;
@@ -66,8 +71,6 @@
 Tkinter_Error (v)
      PyObject *v;
 {
-  if (Tkapp_Check (v))
-    PyErr_BadInternalCall ();
   PyErr_SetString (Tkinter_TclError, Tkapp_Result (v));
   return NULL;
 }
@@ -688,6 +691,7 @@
   
   res = PyEval_CallObject (func, arg);
   Py_DECREF (arg);
+
   if (res == NULL)
     return PythonCmd_Error (interp);
 
@@ -835,8 +839,6 @@
 
 /** Event Loop **/
 
-static int quitMainLoop;
-
 static PyObject *
 Tkapp_MainLoop (self, args)
      PyObject *self;
@@ -1023,9 +1025,19 @@
   /* Do nothing. */
 }
 
+static void
+Tkinter_Cleanup ()
+{
+  /* XXX rl_deprep_terminal is static, damned! */
+  while (tkMainWindowList != 0)
+    Tk_DestroyWindow (tkMainWindowList->win);
+}
+
 void
 PyInit_tkinter ()
 {
+  static inited = 0;
+
 #ifdef WITH_READLINE
   extern int (*rl_event_hook) ();
 #endif /* WITH_READLINE */
@@ -1045,12 +1057,20 @@
   PyDict_SetItemString (d, "EXCEPTION", v);
 
   /* Unblock stdin. */
-  Tk_CreateFileHandler (0, TK_READABLE, StdinProc, (ClientData) 0);
+  if (isatty (0))
+    Tk_CreateFileHandler (0, TK_READABLE, StdinProc, (ClientData) 0);
 
 #ifdef WITH_READLINE
   rl_event_hook = EventHook;
 #endif /* WITH_READLINE */
 
+  if (!inited)
+    {
+      inited = 1;
+      if (atexit (Tkinter_Cleanup))
+	PyErr_SetFromErrno (Tkinter_TclError);
+    }
+
   if (PyErr_Occurred ())
     Py_FatalError ("can't initialize module tkinter");
 }