Issue #8716: Avoid crashes caused by Aqua Tk on OSX when attempting to run
test_tk or test_ttk_guionly under a username that is not currently logged
in to the console windowserver (as may be the case under buildbot or ssh).
diff --git a/Lib/test/test_tk.py b/Lib/test/test_tk.py
index 49ca53f..8625db2 100644
--- a/Lib/test/test_tk.py
+++ b/Lib/test/test_tk.py
@@ -1,18 +1,9 @@
 import os
-import unittest
 from test import test_support
 
 # Skip test if _tkinter wasn't built.
 test_support.import_module('_tkinter')
 
-import Tkinter
-
-try:
-    Tkinter.Button()
-except Tkinter.TclError, msg:
-    # assuming tk is not available
-    raise unittest.SkipTest("tk not available: %s" % msg)
-
 this_dir = os.path.dirname(os.path.abspath(__file__))
 lib_tk_test = os.path.abspath(os.path.join(this_dir, os.path.pardir,
     'lib-tk', 'test'))
@@ -20,6 +11,9 @@
 with test_support.DirsOnSysPath(lib_tk_test):
     import runtktests
 
+# Skip test if tk cannot be initialized.
+runtktests.check_tk_availability()
+
 def test_main(enable_gui=False):
     if enable_gui:
         if test_support.use_resources is None:
diff --git a/Lib/test/test_ttk_guionly.py b/Lib/test/test_ttk_guionly.py
index 60a57f0..e0368be 100644
--- a/Lib/test/test_ttk_guionly.py
+++ b/Lib/test/test_ttk_guionly.py
@@ -5,6 +5,16 @@
 # Skip this test if _tkinter wasn't built.
 test_support.import_module('_tkinter')
 
+this_dir = os.path.dirname(os.path.abspath(__file__))
+lib_tk_test = os.path.abspath(os.path.join(this_dir, os.path.pardir,
+    'lib-tk', 'test'))
+
+with test_support.DirsOnSysPath(lib_tk_test):
+    import runtktests
+
+# Skip test if tk cannot be initialized.
+runtktests.check_tk_availability()
+
 import ttk
 from _tkinter import TclError
 
@@ -14,13 +24,6 @@
     # assuming ttk is not available
     raise unittest.SkipTest("ttk not available: %s" % msg)
 
-this_dir = os.path.dirname(os.path.abspath(__file__))
-lib_tk_test = os.path.abspath(os.path.join(this_dir, os.path.pardir,
-    'lib-tk', 'test'))
-
-with test_support.DirsOnSysPath(lib_tk_test):
-    import runtktests
-
 def test_main(enable_gui=False):
     if enable_gui:
         if test_support.use_resources is None: