##// END OF EJS Templates
Deprecation warnings for enable_* functions in inputhook...
Thomas Kluyver -
Show More
@@ -1,560 +1,569 b''
1 # coding: utf-8
1 # coding: utf-8
2 """
2 """
3 Inputhook management for GUI event loop integration.
3 Inputhook management for GUI event loop integration.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 try:
17 try:
18 import ctypes
18 import ctypes
19 except ImportError:
19 except ImportError:
20 ctypes = None
20 ctypes = None
21 except SystemError: # IronPython issue, 2/8/2014
21 except SystemError: # IronPython issue, 2/8/2014
22 ctypes = None
22 ctypes = None
23 import os
23 import os
24 import sys
24 import sys
25 from distutils.version import LooseVersion as V
25 from distutils.version import LooseVersion as V
26
26
27 from IPython.utils.warn import warn
27 from IPython.utils.warn import warn
28
28
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30 # Constants
30 # Constants
31 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
32
32
33 # Constants for identifying the GUI toolkits.
33 # Constants for identifying the GUI toolkits.
34 GUI_WX = 'wx'
34 GUI_WX = 'wx'
35 GUI_QT = 'qt'
35 GUI_QT = 'qt'
36 GUI_QT4 = 'qt4'
36 GUI_QT4 = 'qt4'
37 GUI_GTK = 'gtk'
37 GUI_GTK = 'gtk'
38 GUI_TK = 'tk'
38 GUI_TK = 'tk'
39 GUI_OSX = 'osx'
39 GUI_OSX = 'osx'
40 GUI_GLUT = 'glut'
40 GUI_GLUT = 'glut'
41 GUI_PYGLET = 'pyglet'
41 GUI_PYGLET = 'pyglet'
42 GUI_GTK3 = 'gtk3'
42 GUI_GTK3 = 'gtk3'
43 GUI_NONE = 'none' # i.e. disable
43 GUI_NONE = 'none' # i.e. disable
44
44
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46 # Utilities
46 # Utilities
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48
48
49 def _stdin_ready_posix():
49 def _stdin_ready_posix():
50 """Return True if there's something to read on stdin (posix version)."""
50 """Return True if there's something to read on stdin (posix version)."""
51 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
51 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
52 return bool(infds)
52 return bool(infds)
53
53
54 def _stdin_ready_nt():
54 def _stdin_ready_nt():
55 """Return True if there's something to read on stdin (nt version)."""
55 """Return True if there's something to read on stdin (nt version)."""
56 return msvcrt.kbhit()
56 return msvcrt.kbhit()
57
57
58 def _stdin_ready_other():
58 def _stdin_ready_other():
59 """Return True, assuming there's something to read on stdin."""
59 """Return True, assuming there's something to read on stdin."""
60 return True #
60 return True #
61
61
62
62
63 def _ignore_CTRL_C_posix():
63 def _ignore_CTRL_C_posix():
64 """Ignore CTRL+C (SIGINT)."""
64 """Ignore CTRL+C (SIGINT)."""
65 signal.signal(signal.SIGINT, signal.SIG_IGN)
65 signal.signal(signal.SIGINT, signal.SIG_IGN)
66
66
67 def _allow_CTRL_C_posix():
67 def _allow_CTRL_C_posix():
68 """Take CTRL+C into account (SIGINT)."""
68 """Take CTRL+C into account (SIGINT)."""
69 signal.signal(signal.SIGINT, signal.default_int_handler)
69 signal.signal(signal.SIGINT, signal.default_int_handler)
70
70
71 def _ignore_CTRL_C_other():
71 def _ignore_CTRL_C_other():
72 """Ignore CTRL+C (not implemented)."""
72 """Ignore CTRL+C (not implemented)."""
73 pass
73 pass
74
74
75 def _allow_CTRL_C_other():
75 def _allow_CTRL_C_other():
76 """Take CTRL+C into account (not implemented)."""
76 """Take CTRL+C into account (not implemented)."""
77 pass
77 pass
78
78
79 if os.name == 'posix':
79 if os.name == 'posix':
80 import select
80 import select
81 import signal
81 import signal
82 stdin_ready = _stdin_ready_posix
82 stdin_ready = _stdin_ready_posix
83 ignore_CTRL_C = _ignore_CTRL_C_posix
83 ignore_CTRL_C = _ignore_CTRL_C_posix
84 allow_CTRL_C = _allow_CTRL_C_posix
84 allow_CTRL_C = _allow_CTRL_C_posix
85 elif os.name == 'nt':
85 elif os.name == 'nt':
86 import msvcrt
86 import msvcrt
87 stdin_ready = _stdin_ready_nt
87 stdin_ready = _stdin_ready_nt
88 ignore_CTRL_C = _ignore_CTRL_C_other
88 ignore_CTRL_C = _ignore_CTRL_C_other
89 allow_CTRL_C = _allow_CTRL_C_other
89 allow_CTRL_C = _allow_CTRL_C_other
90 else:
90 else:
91 stdin_ready = _stdin_ready_other
91 stdin_ready = _stdin_ready_other
92 ignore_CTRL_C = _ignore_CTRL_C_other
92 ignore_CTRL_C = _ignore_CTRL_C_other
93 allow_CTRL_C = _allow_CTRL_C_other
93 allow_CTRL_C = _allow_CTRL_C_other
94
94
95
95
96 #-----------------------------------------------------------------------------
96 #-----------------------------------------------------------------------------
97 # Main InputHookManager class
97 # Main InputHookManager class
98 #-----------------------------------------------------------------------------
98 #-----------------------------------------------------------------------------
99
99
100
100
101 class InputHookManager(object):
101 class InputHookManager(object):
102 """Manage PyOS_InputHook for different GUI toolkits.
102 """Manage PyOS_InputHook for different GUI toolkits.
103
103
104 This class installs various hooks under ``PyOSInputHook`` to handle
104 This class installs various hooks under ``PyOSInputHook`` to handle
105 GUI event loop integration.
105 GUI event loop integration.
106 """
106 """
107
107
108 def __init__(self):
108 def __init__(self):
109 if ctypes is None:
109 if ctypes is None:
110 warn("IPython GUI event loop requires ctypes, %gui will not be available")
110 warn("IPython GUI event loop requires ctypes, %gui will not be available")
111 return
111 return
112 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
112 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
113 self.guihooks = {}
113 self.guihooks = {}
114 self.aliases = {}
114 self.aliases = {}
115 self.apps = {}
115 self.apps = {}
116 self._reset()
116 self._reset()
117
117
118 def _reset(self):
118 def _reset(self):
119 self._callback_pyfunctype = None
119 self._callback_pyfunctype = None
120 self._callback = None
120 self._callback = None
121 self._installed = False
121 self._installed = False
122 self._current_gui = None
122 self._current_gui = None
123
123
124 def get_pyos_inputhook(self):
124 def get_pyos_inputhook(self):
125 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
125 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
126 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
126 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
127
127
128 def get_pyos_inputhook_as_func(self):
128 def get_pyos_inputhook_as_func(self):
129 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
129 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
130 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
130 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
131
131
132 def set_inputhook(self, callback):
132 def set_inputhook(self, callback):
133 """Set PyOS_InputHook to callback and return the previous one."""
133 """Set PyOS_InputHook to callback and return the previous one."""
134 # On platforms with 'readline' support, it's all too likely to
134 # On platforms with 'readline' support, it's all too likely to
135 # have a KeyboardInterrupt signal delivered *even before* an
135 # have a KeyboardInterrupt signal delivered *even before* an
136 # initial ``try:`` clause in the callback can be executed, so
136 # initial ``try:`` clause in the callback can be executed, so
137 # we need to disable CTRL+C in this situation.
137 # we need to disable CTRL+C in this situation.
138 ignore_CTRL_C()
138 ignore_CTRL_C()
139 self._callback = callback
139 self._callback = callback
140 self._callback_pyfunctype = self.PYFUNC(callback)
140 self._callback_pyfunctype = self.PYFUNC(callback)
141 pyos_inputhook_ptr = self.get_pyos_inputhook()
141 pyos_inputhook_ptr = self.get_pyos_inputhook()
142 original = self.get_pyos_inputhook_as_func()
142 original = self.get_pyos_inputhook_as_func()
143 pyos_inputhook_ptr.value = \
143 pyos_inputhook_ptr.value = \
144 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
144 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
145 self._installed = True
145 self._installed = True
146 return original
146 return original
147
147
148 def clear_inputhook(self, app=None):
148 def clear_inputhook(self, app=None):
149 """Set PyOS_InputHook to NULL and return the previous one.
149 """Set PyOS_InputHook to NULL and return the previous one.
150
150
151 Parameters
151 Parameters
152 ----------
152 ----------
153 app : optional, ignored
153 app : optional, ignored
154 This parameter is allowed only so that clear_inputhook() can be
154 This parameter is allowed only so that clear_inputhook() can be
155 called with a similar interface as all the ``enable_*`` methods. But
155 called with a similar interface as all the ``enable_*`` methods. But
156 the actual value of the parameter is ignored. This uniform interface
156 the actual value of the parameter is ignored. This uniform interface
157 makes it easier to have user-level entry points in the main IPython
157 makes it easier to have user-level entry points in the main IPython
158 app like :meth:`enable_gui`."""
158 app like :meth:`enable_gui`."""
159 pyos_inputhook_ptr = self.get_pyos_inputhook()
159 pyos_inputhook_ptr = self.get_pyos_inputhook()
160 original = self.get_pyos_inputhook_as_func()
160 original = self.get_pyos_inputhook_as_func()
161 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
161 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
162 allow_CTRL_C()
162 allow_CTRL_C()
163 self._reset()
163 self._reset()
164 return original
164 return original
165
165
166 def clear_app_refs(self, gui=None):
166 def clear_app_refs(self, gui=None):
167 """Clear IPython's internal reference to an application instance.
167 """Clear IPython's internal reference to an application instance.
168
168
169 Whenever we create an app for a user on qt4 or wx, we hold a
169 Whenever we create an app for a user on qt4 or wx, we hold a
170 reference to the app. This is needed because in some cases bad things
170 reference to the app. This is needed because in some cases bad things
171 can happen if a user doesn't hold a reference themselves. This
171 can happen if a user doesn't hold a reference themselves. This
172 method is provided to clear the references we are holding.
172 method is provided to clear the references we are holding.
173
173
174 Parameters
174 Parameters
175 ----------
175 ----------
176 gui : None or str
176 gui : None or str
177 If None, clear all app references. If ('wx', 'qt4') clear
177 If None, clear all app references. If ('wx', 'qt4') clear
178 the app for that toolkit. References are not held for gtk or tk
178 the app for that toolkit. References are not held for gtk or tk
179 as those toolkits don't have the notion of an app.
179 as those toolkits don't have the notion of an app.
180 """
180 """
181 if gui is None:
181 if gui is None:
182 self.apps = {}
182 self.apps = {}
183 elif gui in self.apps:
183 elif gui in self.apps:
184 del self.apps[gui]
184 del self.apps[gui]
185
185
186 def register(self, toolkitname, *aliases):
186 def register(self, toolkitname, *aliases):
187 """Register a class to provide the event loop for a given GUI.
187 """Register a class to provide the event loop for a given GUI.
188
188
189 This is intended to be used as a class decorator. It should be passed
189 This is intended to be used as a class decorator. It should be passed
190 the names with which to register this GUI integration. The classes
190 the names with which to register this GUI integration. The classes
191 themselves should subclass :class:`InputHookBase`.
191 themselves should subclass :class:`InputHookBase`.
192
192
193 ::
193 ::
194
194
195 @inputhook_manager.register('qt')
195 @inputhook_manager.register('qt')
196 class QtInputHook(InputHookBase):
196 class QtInputHook(InputHookBase):
197 def enable(self, app=None):
197 def enable(self, app=None):
198 ...
198 ...
199 """
199 """
200 def decorator(cls):
200 def decorator(cls):
201 inst = cls(self)
201 inst = cls(self)
202 self.guihooks[toolkitname] = inst
202 self.guihooks[toolkitname] = inst
203 for a in aliases:
203 for a in aliases:
204 self.aliases[a] = toolkitname
204 self.aliases[a] = toolkitname
205 return cls
205 return cls
206 return decorator
206 return decorator
207
207
208 def current_gui(self):
208 def current_gui(self):
209 """Return a string indicating the currently active GUI or None."""
209 """Return a string indicating the currently active GUI or None."""
210 return self._current_gui
210 return self._current_gui
211
211
212 def enable_gui(self, gui=None, app=None):
212 def enable_gui(self, gui=None, app=None):
213 """Switch amongst GUI input hooks by name.
213 """Switch amongst GUI input hooks by name.
214
214
215 This is a higher level method than :meth:`set_inputhook` - it uses the
215 This is a higher level method than :meth:`set_inputhook` - it uses the
216 GUI name to look up a registered object which enables the input hook
216 GUI name to look up a registered object which enables the input hook
217 for that GUI.
217 for that GUI.
218
218
219 Parameters
219 Parameters
220 ----------
220 ----------
221 gui : optional, string or None
221 gui : optional, string or None
222 If None (or 'none'), clears input hook, otherwise it must be one
222 If None (or 'none'), clears input hook, otherwise it must be one
223 of the recognized GUI names (see ``GUI_*`` constants in module).
223 of the recognized GUI names (see ``GUI_*`` constants in module).
224
224
225 app : optional, existing application object.
225 app : optional, existing application object.
226 For toolkits that have the concept of a global app, you can supply an
226 For toolkits that have the concept of a global app, you can supply an
227 existing one. If not given, the toolkit will be probed for one, and if
227 existing one. If not given, the toolkit will be probed for one, and if
228 none is found, a new one will be created. Note that GTK does not have
228 none is found, a new one will be created. Note that GTK does not have
229 this concept, and passing an app if ``gui=="GTK"`` will raise an error.
229 this concept, and passing an app if ``gui=="GTK"`` will raise an error.
230
230
231 Returns
231 Returns
232 -------
232 -------
233 The output of the underlying gui switch routine, typically the actual
233 The output of the underlying gui switch routine, typically the actual
234 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
234 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
235 one.
235 one.
236 """
236 """
237 if gui in (None, GUI_NONE):
237 if gui in (None, GUI_NONE):
238 return self.disable_gui()
238 return self.disable_gui()
239
239
240 if gui in self.aliases:
240 if gui in self.aliases:
241 return self.enable_gui(self.aliases[gui], app)
241 return self.enable_gui(self.aliases[gui], app)
242
242
243 try:
243 try:
244 gui_hook = self.guihooks[gui]
244 gui_hook = self.guihooks[gui]
245 except KeyError:
245 except KeyError:
246 e = "Invalid GUI request {!r}, valid ones are: {}"
246 e = "Invalid GUI request {!r}, valid ones are: {}"
247 raise ValueError(e.format(gui, ', '.join(self.guihooks)))
247 raise ValueError(e.format(gui, ', '.join(self.guihooks)))
248 self._current_gui = gui
248 self._current_gui = gui
249 return gui_hook.enable(app)
249 return gui_hook.enable(app)
250
250
251 def disable_gui(self):
251 def disable_gui(self):
252 """Disable GUI event loop integration.
252 """Disable GUI event loop integration.
253
253
254 If an application was registered, this sets its ``_in_event_loop``
254 If an application was registered, this sets its ``_in_event_loop``
255 attribute to False. It then calls :meth:`clear_inputhook`.
255 attribute to False. It then calls :meth:`clear_inputhook`.
256 """
256 """
257 gui = self._current_gui
257 gui = self._current_gui
258 if gui in self.apps:
258 if gui in self.apps:
259 self.apps[gui]._in_event_loop = False
259 self.apps[gui]._in_event_loop = False
260 return self.clear_inputhook()
260 return self.clear_inputhook()
261
261
262 class InputHookBase(object):
262 class InputHookBase(object):
263 """Base class for input hooks for specific toolkits.
263 """Base class for input hooks for specific toolkits.
264
264
265 Subclasses should define an :meth:`enable` method with one argument, ``app``,
265 Subclasses should define an :meth:`enable` method with one argument, ``app``,
266 which will either be an instance of the toolkit's application class, or None.
266 which will either be an instance of the toolkit's application class, or None.
267 They may also define a :meth:`disable` method with no arguments.
267 They may also define a :meth:`disable` method with no arguments.
268 """
268 """
269 def __init__(self, manager):
269 def __init__(self, manager):
270 self.manager = manager
270 self.manager = manager
271
271
272 def disable(self):
272 def disable(self):
273 pass
273 pass
274
274
275 inputhook_manager = InputHookManager()
275 inputhook_manager = InputHookManager()
276
276
277 @inputhook_manager.register('wx')
277 @inputhook_manager.register('wx')
278 class WxInputHook(InputHookBase):
278 class WxInputHook(InputHookBase):
279 def enable(self, app=None):
279 def enable(self, app=None):
280 """Enable event loop integration with wxPython.
280 """Enable event loop integration with wxPython.
281
281
282 Parameters
282 Parameters
283 ----------
283 ----------
284 app : WX Application, optional.
284 app : WX Application, optional.
285 Running application to use. If not given, we probe WX for an
285 Running application to use. If not given, we probe WX for an
286 existing application object, and create a new one if none is found.
286 existing application object, and create a new one if none is found.
287
287
288 Notes
288 Notes
289 -----
289 -----
290 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
290 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
291 the wxPython to integrate with terminal based applications like
291 the wxPython to integrate with terminal based applications like
292 IPython.
292 IPython.
293
293
294 If ``app`` is not given we probe for an existing one, and return it if
294 If ``app`` is not given we probe for an existing one, and return it if
295 found. If no existing app is found, we create an :class:`wx.App` as
295 found. If no existing app is found, we create an :class:`wx.App` as
296 follows::
296 follows::
297
297
298 import wx
298 import wx
299 app = wx.App(redirect=False, clearSigInt=False)
299 app = wx.App(redirect=False, clearSigInt=False)
300 """
300 """
301 import wx
301 import wx
302
302
303 wx_version = V(wx.__version__).version
303 wx_version = V(wx.__version__).version
304
304
305 if wx_version < [2, 8]:
305 if wx_version < [2, 8]:
306 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
306 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
307
307
308 from IPython.lib.inputhookwx import inputhook_wx
308 from IPython.lib.inputhookwx import inputhook_wx
309 from IPython.external.appnope import nope
309 from IPython.external.appnope import nope
310 self.manager.set_inputhook(inputhook_wx)
310 self.manager.set_inputhook(inputhook_wx)
311 nope()
311 nope()
312
312
313 import wx
313 import wx
314 if app is None:
314 if app is None:
315 app = wx.GetApp()
315 app = wx.GetApp()
316 if app is None:
316 if app is None:
317 app = wx.App(redirect=False, clearSigInt=False)
317 app = wx.App(redirect=False, clearSigInt=False)
318 app._in_event_loop = True
318 app._in_event_loop = True
319 self.manager.apps[GUI_WX] = app
319 self.manager.apps[GUI_WX] = app
320 return app
320 return app
321
321
322 def disable(self):
322 def disable(self):
323 """Disable event loop integration with wxPython.
323 """Disable event loop integration with wxPython.
324
324
325 This restores appnapp on OS X
325 This restores appnapp on OS X
326 """
326 """
327 from IPython.external.appnope import nap
327 from IPython.external.appnope import nap
328 nap()
328 nap()
329
329
330 @inputhook_manager.register('qt', 'qt4')
330 @inputhook_manager.register('qt', 'qt4')
331 class Qt4InputHook(InputHookBase):
331 class Qt4InputHook(InputHookBase):
332 def enable(self, app=None):
332 def enable(self, app=None):
333 """Enable event loop integration with PyQt4.
333 """Enable event loop integration with PyQt4.
334
334
335 Parameters
335 Parameters
336 ----------
336 ----------
337 app : Qt Application, optional.
337 app : Qt Application, optional.
338 Running application to use. If not given, we probe Qt for an
338 Running application to use. If not given, we probe Qt for an
339 existing application object, and create a new one if none is found.
339 existing application object, and create a new one if none is found.
340
340
341 Notes
341 Notes
342 -----
342 -----
343 This methods sets the PyOS_InputHook for PyQt4, which allows
343 This methods sets the PyOS_InputHook for PyQt4, which allows
344 the PyQt4 to integrate with terminal based applications like
344 the PyQt4 to integrate with terminal based applications like
345 IPython.
345 IPython.
346
346
347 If ``app`` is not given we probe for an existing one, and return it if
347 If ``app`` is not given we probe for an existing one, and return it if
348 found. If no existing app is found, we create an :class:`QApplication`
348 found. If no existing app is found, we create an :class:`QApplication`
349 as follows::
349 as follows::
350
350
351 from PyQt4 import QtCore
351 from PyQt4 import QtCore
352 app = QtGui.QApplication(sys.argv)
352 app = QtGui.QApplication(sys.argv)
353 """
353 """
354 from IPython.lib.inputhookqt4 import create_inputhook_qt4
354 from IPython.lib.inputhookqt4 import create_inputhook_qt4
355 from IPython.external.appnope import nope
355 from IPython.external.appnope import nope
356 app, inputhook_qt4 = create_inputhook_qt4(self, app)
356 app, inputhook_qt4 = create_inputhook_qt4(self, app)
357 self.manager.set_inputhook(inputhook_qt4)
357 self.manager.set_inputhook(inputhook_qt4)
358 nope()
358 nope()
359
359
360 app._in_event_loop = True
360 app._in_event_loop = True
361 self.manager.apps[GUI_QT4] = app
361 self.manager.apps[GUI_QT4] = app
362 return app
362 return app
363
363
364 def disable_qt4(self):
364 def disable_qt4(self):
365 """Disable event loop integration with PyQt4.
365 """Disable event loop integration with PyQt4.
366
366
367 This restores appnapp on OS X
367 This restores appnapp on OS X
368 """
368 """
369 from IPython.external.appnope import nap
369 from IPython.external.appnope import nap
370 nap()
370 nap()
371
371
372 @inputhook_manager.register('gtk')
372 @inputhook_manager.register('gtk')
373 class GtkInputHook(InputHookBase):
373 class GtkInputHook(InputHookBase):
374 def enable(self, app=None):
374 def enable(self, app=None):
375 """Enable event loop integration with PyGTK.
375 """Enable event loop integration with PyGTK.
376
376
377 Parameters
377 Parameters
378 ----------
378 ----------
379 app : ignored
379 app : ignored
380 Ignored, it's only a placeholder to keep the call signature of all
380 Ignored, it's only a placeholder to keep the call signature of all
381 gui activation methods consistent, which simplifies the logic of
381 gui activation methods consistent, which simplifies the logic of
382 supporting magics.
382 supporting magics.
383
383
384 Notes
384 Notes
385 -----
385 -----
386 This methods sets the PyOS_InputHook for PyGTK, which allows
386 This methods sets the PyOS_InputHook for PyGTK, which allows
387 the PyGTK to integrate with terminal based applications like
387 the PyGTK to integrate with terminal based applications like
388 IPython.
388 IPython.
389 """
389 """
390 import gtk
390 import gtk
391 try:
391 try:
392 gtk.set_interactive(True)
392 gtk.set_interactive(True)
393 except AttributeError:
393 except AttributeError:
394 # For older versions of gtk, use our own ctypes version
394 # For older versions of gtk, use our own ctypes version
395 from IPython.lib.inputhookgtk import inputhook_gtk
395 from IPython.lib.inputhookgtk import inputhook_gtk
396 self.manager.set_inputhook(inputhook_gtk)
396 self.manager.set_inputhook(inputhook_gtk)
397
397
398
398
399 @inputhook_manager.register('tk')
399 @inputhook_manager.register('tk')
400 class TkInputHook(InputHookBase):
400 class TkInputHook(InputHookBase):
401 def enable(self, app=None):
401 def enable(self, app=None):
402 """Enable event loop integration with Tk.
402 """Enable event loop integration with Tk.
403
403
404 Parameters
404 Parameters
405 ----------
405 ----------
406 app : toplevel :class:`Tkinter.Tk` widget, optional.
406 app : toplevel :class:`Tkinter.Tk` widget, optional.
407 Running toplevel widget to use. If not given, we probe Tk for an
407 Running toplevel widget to use. If not given, we probe Tk for an
408 existing one, and create a new one if none is found.
408 existing one, and create a new one if none is found.
409
409
410 Notes
410 Notes
411 -----
411 -----
412 If you have already created a :class:`Tkinter.Tk` object, the only
412 If you have already created a :class:`Tkinter.Tk` object, the only
413 thing done by this method is to register with the
413 thing done by this method is to register with the
414 :class:`InputHookManager`, since creating that object automatically
414 :class:`InputHookManager`, since creating that object automatically
415 sets ``PyOS_InputHook``.
415 sets ``PyOS_InputHook``.
416 """
416 """
417 if app is None:
417 if app is None:
418 try:
418 try:
419 from tkinter import Tk # Py 3
419 from tkinter import Tk # Py 3
420 except ImportError:
420 except ImportError:
421 from Tkinter import Tk # Py 2
421 from Tkinter import Tk # Py 2
422 app = Tk()
422 app = Tk()
423 app.withdraw()
423 app.withdraw()
424 self.manager.apps[GUI_TK] = app
424 self.manager.apps[GUI_TK] = app
425 return app
425 return app
426
426
427
427
428 @inputhook_manager.register('glut')
428 @inputhook_manager.register('glut')
429 class GlutInputHook(InputHookBase):
429 class GlutInputHook(InputHookBase):
430 def enable(self, app=None):
430 def enable(self, app=None):
431 """Enable event loop integration with GLUT.
431 """Enable event loop integration with GLUT.
432
432
433 Parameters
433 Parameters
434 ----------
434 ----------
435
435
436 app : ignored
436 app : ignored
437 Ignored, it's only a placeholder to keep the call signature of all
437 Ignored, it's only a placeholder to keep the call signature of all
438 gui activation methods consistent, which simplifies the logic of
438 gui activation methods consistent, which simplifies the logic of
439 supporting magics.
439 supporting magics.
440
440
441 Notes
441 Notes
442 -----
442 -----
443
443
444 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
444 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
445 integrate with terminal based applications like IPython. Due to GLUT
445 integrate with terminal based applications like IPython. Due to GLUT
446 limitations, it is currently not possible to start the event loop
446 limitations, it is currently not possible to start the event loop
447 without first creating a window. You should thus not create another
447 without first creating a window. You should thus not create another
448 window but use instead the created one. See 'gui-glut.py' in the
448 window but use instead the created one. See 'gui-glut.py' in the
449 docs/examples/lib directory.
449 docs/examples/lib directory.
450
450
451 The default screen mode is set to:
451 The default screen mode is set to:
452 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
452 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
453 """
453 """
454
454
455 import OpenGL.GLUT as glut
455 import OpenGL.GLUT as glut
456 from IPython.lib.inputhookglut import glut_display_mode, \
456 from IPython.lib.inputhookglut import glut_display_mode, \
457 glut_close, glut_display, \
457 glut_close, glut_display, \
458 glut_idle, inputhook_glut
458 glut_idle, inputhook_glut
459
459
460 if GUI_GLUT not in self.manager.apps:
460 if GUI_GLUT not in self.manager.apps:
461 glut.glutInit( sys.argv )
461 glut.glutInit( sys.argv )
462 glut.glutInitDisplayMode( glut_display_mode )
462 glut.glutInitDisplayMode( glut_display_mode )
463 # This is specific to freeglut
463 # This is specific to freeglut
464 if bool(glut.glutSetOption):
464 if bool(glut.glutSetOption):
465 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
465 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
466 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
466 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
467 glut.glutCreateWindow( sys.argv[0] )
467 glut.glutCreateWindow( sys.argv[0] )
468 glut.glutReshapeWindow( 1, 1 )
468 glut.glutReshapeWindow( 1, 1 )
469 glut.glutHideWindow( )
469 glut.glutHideWindow( )
470 glut.glutWMCloseFunc( glut_close )
470 glut.glutWMCloseFunc( glut_close )
471 glut.glutDisplayFunc( glut_display )
471 glut.glutDisplayFunc( glut_display )
472 glut.glutIdleFunc( glut_idle )
472 glut.glutIdleFunc( glut_idle )
473 else:
473 else:
474 glut.glutWMCloseFunc( glut_close )
474 glut.glutWMCloseFunc( glut_close )
475 glut.glutDisplayFunc( glut_display )
475 glut.glutDisplayFunc( glut_display )
476 glut.glutIdleFunc( glut_idle)
476 glut.glutIdleFunc( glut_idle)
477 self.manager.set_inputhook( inputhook_glut )
477 self.manager.set_inputhook( inputhook_glut )
478 self.manager.apps[GUI_GLUT] = True
478 self.manager.apps[GUI_GLUT] = True
479
479
480
480
481 def disable(self):
481 def disable(self):
482 """Disable event loop integration with glut.
482 """Disable event loop integration with glut.
483
483
484 This sets PyOS_InputHook to NULL and set the display function to a
484 This sets PyOS_InputHook to NULL and set the display function to a
485 dummy one and set the timer to a dummy timer that will be triggered
485 dummy one and set the timer to a dummy timer that will be triggered
486 very far in the future.
486 very far in the future.
487 """
487 """
488 import OpenGL.GLUT as glut
488 import OpenGL.GLUT as glut
489 from glut_support import glutMainLoopEvent
489 from glut_support import glutMainLoopEvent
490
490
491 glut.glutHideWindow() # This is an event to be processed below
491 glut.glutHideWindow() # This is an event to be processed below
492 glutMainLoopEvent()
492 glutMainLoopEvent()
493 super(GlutInputHook, self).disable()
493 super(GlutInputHook, self).disable()
494
494
495 @inputhook_manager.register('pyglet')
495 @inputhook_manager.register('pyglet')
496 class PygletInputHook(InputHookBase):
496 class PygletInputHook(InputHookBase):
497 def enable(self, app=None):
497 def enable(self, app=None):
498 """Enable event loop integration with pyglet.
498 """Enable event loop integration with pyglet.
499
499
500 Parameters
500 Parameters
501 ----------
501 ----------
502 app : ignored
502 app : ignored
503 Ignored, it's only a placeholder to keep the call signature of all
503 Ignored, it's only a placeholder to keep the call signature of all
504 gui activation methods consistent, which simplifies the logic of
504 gui activation methods consistent, which simplifies the logic of
505 supporting magics.
505 supporting magics.
506
506
507 Notes
507 Notes
508 -----
508 -----
509 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
509 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
510 pyglet to integrate with terminal based applications like
510 pyglet to integrate with terminal based applications like
511 IPython.
511 IPython.
512
512
513 """
513 """
514 from IPython.lib.inputhookpyglet import inputhook_pyglet
514 from IPython.lib.inputhookpyglet import inputhook_pyglet
515 self.manager.set_inputhook(inputhook_pyglet)
515 self.manager.set_inputhook(inputhook_pyglet)
516 return app
516 return app
517
517
518
518
519 @inputhook_manager.register('gtk3')
519 @inputhook_manager.register('gtk3')
520 class Gtk3InputHook(InputHookBase):
520 class Gtk3InputHook(InputHookBase):
521 def enable(self, app=None):
521 def enable(self, app=None):
522 """Enable event loop integration with Gtk3 (gir bindings).
522 """Enable event loop integration with Gtk3 (gir bindings).
523
523
524 Parameters
524 Parameters
525 ----------
525 ----------
526 app : ignored
526 app : ignored
527 Ignored, it's only a placeholder to keep the call signature of all
527 Ignored, it's only a placeholder to keep the call signature of all
528 gui activation methods consistent, which simplifies the logic of
528 gui activation methods consistent, which simplifies the logic of
529 supporting magics.
529 supporting magics.
530
530
531 Notes
531 Notes
532 -----
532 -----
533 This methods sets the PyOS_InputHook for Gtk3, which allows
533 This methods sets the PyOS_InputHook for Gtk3, which allows
534 the Gtk3 to integrate with terminal based applications like
534 the Gtk3 to integrate with terminal based applications like
535 IPython.
535 IPython.
536 """
536 """
537 from IPython.lib.inputhookgtk3 import inputhook_gtk3
537 from IPython.lib.inputhookgtk3 import inputhook_gtk3
538 self.manager.set_inputhook(inputhook_gtk3)
538 self.manager.set_inputhook(inputhook_gtk3)
539 self.manager._current_gui = GUI_GTK
539 self.manager._current_gui = GUI_GTK
540
540
541
541
542 clear_inputhook = inputhook_manager.clear_inputhook
542 clear_inputhook = inputhook_manager.clear_inputhook
543 set_inputhook = inputhook_manager.set_inputhook
543 set_inputhook = inputhook_manager.set_inputhook
544 current_gui = inputhook_manager.current_gui
544 current_gui = inputhook_manager.current_gui
545 clear_app_refs = inputhook_manager.clear_app_refs
545 clear_app_refs = inputhook_manager.clear_app_refs
546 enable_gui = inputhook_manager.enable_gui
546 enable_gui = inputhook_manager.enable_gui
547 disable_gui = inputhook_manager.disable_gui
547 disable_gui = inputhook_manager.disable_gui
548 register = inputhook_manager.register
548 register = inputhook_manager.register
549 guis = inputhook_manager.guihooks
549 guis = inputhook_manager.guihooks
550
550
551 # Deprecated methods: kept for backwards compatibility, do not use in new code
551 # Deprecated methods: kept for backwards compatibility, do not use in new code
552 enable_wx = lambda app=None: inputhook_manager.enable_gui('wx', app)
552 def _make_deprecated_enable(name):
553 enable_qt4 = lambda app=None: inputhook_manager.enable_gui('qt4', app)
553 def enable_toolkit(app=None):
554 enable_gtk = lambda app=None: inputhook_manager.enable_gui('gtk', app)
554 warn("This function is deprecated - use enable_gui(%r) instead" % name)
555 enable_tk = lambda app=None: inputhook_manager.enable_gui('tk', app)
555 inputhook_manager.enable_gui(name, app)
556 enable_glut = lambda app=None: inputhook_manager.enable_gui('glut', app)
556
557 enable_pyglet = lambda app=None: inputhook_manager.enable_gui('pyglet', app)
557 enable_wx = _make_deprecated_enable('wx')
558 enable_gtk3 = lambda app=None: inputhook_manager.enable_gui('gtk3', app)
558 enable_qt4 = _make_deprecated_enable('qt4')
559 enable_gtk = _make_deprecated_enable('gtk')
560 enable_tk = _make_deprecated_enable('tk')
561 enable_glut = _make_deprecated_enable('glut')
562 enable_pyglet = _make_deprecated_enable('pyglet')
563 enable_gtk3 = _make_deprecated_enable('gtk3')
564
565 def _deprecated_disable():
566 warn("This function is deprecated: use disable_gui() instead")
567 inputhook_manager.disable_gui()
559 disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \
568 disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \
560 disable_pyglet = inputhook_manager.disable_gui No newline at end of file
569 disable_pyglet = _deprecated_disable
@@ -1,39 +1,39 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Simple GTK example to manually test event loop integration.
2 """Simple GTK example to manually test event loop integration.
3
3
4 This is meant to run tests manually in ipython as:
4 This is meant to run tests manually in ipython as:
5
5
6 In [5]: %gui gtk
6 In [5]: %gui gtk
7
7
8 In [6]: %run gui-gtk.py
8 In [6]: %run gui-gtk.py
9 """
9 """
10
10
11 import pygtk
11 import pygtk
12 pygtk.require('2.0')
12 pygtk.require('2.0')
13 import gtk
13 import gtk
14
14
15
15
16 def hello_world(wigdet, data=None):
16 def hello_world(wigdet, data=None):
17 print("Hello World")
17 print("Hello World")
18
18
19 def delete_event(widget, event, data=None):
19 def delete_event(widget, event, data=None):
20 return False
20 return False
21
21
22 def destroy(widget, data=None):
22 def destroy(widget, data=None):
23 gtk.main_quit()
23 gtk.main_quit()
24
24
25 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
25 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
26 window.connect("delete_event", delete_event)
26 window.connect("delete_event", delete_event)
27 window.connect("destroy", destroy)
27 window.connect("destroy", destroy)
28 button = gtk.Button("Hello World")
28 button = gtk.Button("Hello World")
29 button.connect("clicked", hello_world, None)
29 button.connect("clicked", hello_world, None)
30
30
31 window.add(button)
31 window.add(button)
32 button.show()
32 button.show()
33 window.show()
33 window.show()
34
34
35 try:
35 try:
36 from IPython.lib.inputhook import enable_gtk
36 from IPython.lib.inputhook import enable_gui
37 enable_gtk()
37 enable_gui('gtk')
38 except ImportError:
38 except ImportError:
39 gtk.main()
39 gtk.main()
@@ -1,37 +1,37 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Simple Gtk example to manually test event loop integration.
2 """Simple Gtk example to manually test event loop integration.
3
3
4 This is meant to run tests manually in ipython as:
4 This is meant to run tests manually in ipython as:
5
5
6 In [1]: %gui gtk3
6 In [1]: %gui gtk3
7
7
8 In [2]: %run gui-gtk3.py
8 In [2]: %run gui-gtk3.py
9 """
9 """
10
10
11 from gi.repository import Gtk
11 from gi.repository import Gtk
12
12
13
13
14 def hello_world(wigdet, data=None):
14 def hello_world(wigdet, data=None):
15 print("Hello World")
15 print("Hello World")
16
16
17 def delete_event(widget, event, data=None):
17 def delete_event(widget, event, data=None):
18 return False
18 return False
19
19
20 def destroy(widget, data=None):
20 def destroy(widget, data=None):
21 Gtk.main_quit()
21 Gtk.main_quit()
22
22
23 window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
23 window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
24 window.connect("delete_event", delete_event)
24 window.connect("delete_event", delete_event)
25 window.connect("destroy", destroy)
25 window.connect("destroy", destroy)
26 button = Gtk.Button("Hello World")
26 button = Gtk.Button("Hello World")
27 button.connect("clicked", hello_world, None)
27 button.connect("clicked", hello_world, None)
28
28
29 window.add(button)
29 window.add(button)
30 button.show()
30 button.show()
31 window.show()
31 window.show()
32
32
33 try:
33 try:
34 from IPython.lib.inputhook import enable_gtk3
34 from IPython.lib.inputhook import enable_gui
35 enable_gtk3()
35 enable_gui('gtk3')
36 except ImportError:
36 except ImportError:
37 Gtk.main()
37 Gtk.main()
@@ -1,33 +1,33 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Simple pyglet example to manually test event loop integration.
2 """Simple pyglet example to manually test event loop integration.
3
3
4 This is meant to run tests manually in ipython as:
4 This is meant to run tests manually in ipython as:
5
5
6 In [5]: %gui pyglet
6 In [5]: %gui pyglet
7
7
8 In [6]: %run gui-pyglet.py
8 In [6]: %run gui-pyglet.py
9 """
9 """
10
10
11 import pyglet
11 import pyglet
12
12
13
13
14 window = pyglet.window.Window()
14 window = pyglet.window.Window()
15 label = pyglet.text.Label('Hello, world',
15 label = pyglet.text.Label('Hello, world',
16 font_name='Times New Roman',
16 font_name='Times New Roman',
17 font_size=36,
17 font_size=36,
18 x=window.width//2, y=window.height//2,
18 x=window.width//2, y=window.height//2,
19 anchor_x='center', anchor_y='center')
19 anchor_x='center', anchor_y='center')
20 @window.event
20 @window.event
21 def on_close():
21 def on_close():
22 window.close()
22 window.close()
23
23
24 @window.event
24 @window.event
25 def on_draw():
25 def on_draw():
26 window.clear()
26 window.clear()
27 label.draw()
27 label.draw()
28
28
29 try:
29 try:
30 from IPython.lib.inputhook import enable_pyglet
30 from IPython.lib.inputhook import enable_gui
31 enable_pyglet()
31 enable_gui('pyglet')
32 except ImportError:
32 except ImportError:
33 pyglet.app.run()
33 pyglet.app.run()
@@ -1,35 +1,36 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Simple Tk example to manually test event loop integration.
2 """Simple Tk example to manually test event loop integration.
3
3
4 This is meant to run tests manually in ipython as:
4 This is meant to run tests manually in ipython as:
5
5
6 In [5]: %gui tk
6 In [5]: %gui tk
7
7
8 In [6]: %run gui-tk.py
8 In [6]: %run gui-tk.py
9 """
9 """
10
10
11 try:
11 try:
12 from tkinter import * # Python 3
12 from tkinter import * # Python 3
13 except ImportError:
13 except ImportError:
14 from Tkinter import * # Python 2
14 from Tkinter import * # Python 2
15
15
16 class MyApp:
16 class MyApp:
17
17
18 def __init__(self, root):
18 def __init__(self, root):
19 frame = Frame(root)
19 frame = Frame(root)
20 frame.pack()
20 frame.pack()
21
21
22 self.button = Button(frame, text="Hello", command=self.hello_world)
22 self.button = Button(frame, text="Hello", command=self.hello_world)
23 self.button.pack(side=LEFT)
23 self.button.pack(side=LEFT)
24
24
25 def hello_world(self):
25 def hello_world(self):
26 print("Hello World!")
26 print("Hello World!")
27
27
28 root = Tk()
28 root = Tk()
29
29
30 app = MyApp(root)
30 app = MyApp(root)
31
31
32 try:
32 try:
33 from IPython.lib.inputhook import enable_tk; enable_tk(root)
33 from IPython.lib.inputhook import enable_gui
34 enable_gui('tk', root)
34 except ImportError:
35 except ImportError:
35 root.mainloop()
36 root.mainloop()
@@ -1,106 +1,106 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """
2 """
3 A Simple wx example to test IPython's event loop integration.
3 A Simple wx example to test IPython's event loop integration.
4
4
5 To run this do:
5 To run this do:
6
6
7 In [5]: %gui wx # or start IPython with '--gui wx'
7 In [5]: %gui wx # or start IPython with '--gui wx'
8
8
9 In [6]: %run gui-wx.py
9 In [6]: %run gui-wx.py
10
10
11 Ref: Modified from wxPython source code wxPython/samples/simple/simple.py
11 Ref: Modified from wxPython source code wxPython/samples/simple/simple.py
12 """
12 """
13
13
14 import wx
14 import wx
15
15
16
16
17 class MyFrame(wx.Frame):
17 class MyFrame(wx.Frame):
18 """
18 """
19 This is MyFrame. It just shows a few controls on a wxPanel,
19 This is MyFrame. It just shows a few controls on a wxPanel,
20 and has a simple menu.
20 and has a simple menu.
21 """
21 """
22 def __init__(self, parent, title):
22 def __init__(self, parent, title):
23 wx.Frame.__init__(self, parent, -1, title,
23 wx.Frame.__init__(self, parent, -1, title,
24 pos=(150, 150), size=(350, 200))
24 pos=(150, 150), size=(350, 200))
25
25
26 # Create the menubar
26 # Create the menubar
27 menuBar = wx.MenuBar()
27 menuBar = wx.MenuBar()
28
28
29 # and a menu
29 # and a menu
30 menu = wx.Menu()
30 menu = wx.Menu()
31
31
32 # add an item to the menu, using \tKeyName automatically
32 # add an item to the menu, using \tKeyName automatically
33 # creates an accelerator, the third param is some help text
33 # creates an accelerator, the third param is some help text
34 # that will show up in the statusbar
34 # that will show up in the statusbar
35 menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
35 menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
36
36
37 # bind the menu event to an event handler
37 # bind the menu event to an event handler
38 self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)
38 self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)
39
39
40 # and put the menu on the menubar
40 # and put the menu on the menubar
41 menuBar.Append(menu, "&File")
41 menuBar.Append(menu, "&File")
42 self.SetMenuBar(menuBar)
42 self.SetMenuBar(menuBar)
43
43
44 self.CreateStatusBar()
44 self.CreateStatusBar()
45
45
46 # Now create the Panel to put the other controls on.
46 # Now create the Panel to put the other controls on.
47 panel = wx.Panel(self)
47 panel = wx.Panel(self)
48
48
49 # and a few controls
49 # and a few controls
50 text = wx.StaticText(panel, -1, "Hello World!")
50 text = wx.StaticText(panel, -1, "Hello World!")
51 text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
51 text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
52 text.SetSize(text.GetBestSize())
52 text.SetSize(text.GetBestSize())
53 btn = wx.Button(panel, -1, "Close")
53 btn = wx.Button(panel, -1, "Close")
54 funbtn = wx.Button(panel, -1, "Just for fun...")
54 funbtn = wx.Button(panel, -1, "Just for fun...")
55
55
56 # bind the button events to handlers
56 # bind the button events to handlers
57 self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btn)
57 self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btn)
58 self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn)
58 self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn)
59
59
60 # Use a sizer to layout the controls, stacked vertically and with
60 # Use a sizer to layout the controls, stacked vertically and with
61 # a 10 pixel border around each
61 # a 10 pixel border around each
62 sizer = wx.BoxSizer(wx.VERTICAL)
62 sizer = wx.BoxSizer(wx.VERTICAL)
63 sizer.Add(text, 0, wx.ALL, 10)
63 sizer.Add(text, 0, wx.ALL, 10)
64 sizer.Add(btn, 0, wx.ALL, 10)
64 sizer.Add(btn, 0, wx.ALL, 10)
65 sizer.Add(funbtn, 0, wx.ALL, 10)
65 sizer.Add(funbtn, 0, wx.ALL, 10)
66 panel.SetSizer(sizer)
66 panel.SetSizer(sizer)
67 panel.Layout()
67 panel.Layout()
68
68
69
69
70 def OnTimeToClose(self, evt):
70 def OnTimeToClose(self, evt):
71 """Event handler for the button click."""
71 """Event handler for the button click."""
72 print("See ya later!")
72 print("See ya later!")
73 self.Close()
73 self.Close()
74
74
75 def OnFunButton(self, evt):
75 def OnFunButton(self, evt):
76 """Event handler for the button click."""
76 """Event handler for the button click."""
77 print("Having fun yet?")
77 print("Having fun yet?")
78
78
79
79
80 class MyApp(wx.App):
80 class MyApp(wx.App):
81 def OnInit(self):
81 def OnInit(self):
82 frame = MyFrame(None, "Simple wxPython App")
82 frame = MyFrame(None, "Simple wxPython App")
83 self.SetTopWindow(frame)
83 self.SetTopWindow(frame)
84
84
85 print("Print statements go to this stdout window by default.")
85 print("Print statements go to this stdout window by default.")
86
86
87 frame.Show(True)
87 frame.Show(True)
88 return True
88 return True
89
89
90
90
91 if __name__ == '__main__':
91 if __name__ == '__main__':
92
92
93 app = wx.GetApp()
93 app = wx.GetApp()
94 if app is None:
94 if app is None:
95 app = MyApp(redirect=False, clearSigInt=False)
95 app = MyApp(redirect=False, clearSigInt=False)
96 else:
96 else:
97 frame = MyFrame(None, "Simple wxPython App")
97 frame = MyFrame(None, "Simple wxPython App")
98 app.SetTopWindow(frame)
98 app.SetTopWindow(frame)
99 print("Print statements go to this stdout window by default.")
99 print("Print statements go to this stdout window by default.")
100 frame.Show(True)
100 frame.Show(True)
101
101
102 try:
102 try:
103 from IPython.lib.inputhook import enable_wx
103 from IPython.lib.inputhook import enable_gui
104 enable_wx(app)
104 enable_gui('wx', app)
105 except ImportError:
105 except ImportError:
106 app.MainLoop()
106 app.MainLoop()
General Comments 0
You need to be logged in to leave comments. Login now