##// END OF EJS Templates
Merge pull request #5666 from takluyver/inputhook-extensible...
Min RK -
r17903:c8c43c8a merge
parent child Browse files
Show More
@@ -0,0 +1,103 b''
1 ================================
2 Integrating with GUI event loops
3 ================================
4
5 When the user types ``%gui qt``, IPython integrates itself with the Qt event
6 loop, so you can use both a GUI and an interactive prompt together. IPython
7 supports a number of common GUI toolkits, but from IPython 3.0, it is possible
8 to integrate other event loops without modifying IPython itself.
9
10 Terminal IPython handles event loops very differently from the IPython kernel,
11 so different steps are needed to integrate with each.
12
13 Event loops in the terminal
14 ---------------------------
15
16 In the terminal, IPython uses a blocking Python function to wait for user input.
17 However, the Python C API provides a hook, :c:func:`PyOS_InputHook`, which is
18 called frequently while waiting for input. This can be set to a function which
19 briefly runs the event loop and then returns.
20
21 IPython provides Python level wrappers for setting and resetting this hook. To
22 use them, subclass :class:`IPython.lib.inputhook.InputHookBase`, and define
23 an ``enable(app=None)`` method, which initialises the event loop and calls
24 ``self.manager.set_inputhook(f)`` with a function which will briefly run the
25 event loop before exiting. Decorate the class with a call to
26 :func:`IPython.lib.inputhook.register`::
27
28 from IPython.lib.inputhook import register, InputHookBase
29
30 @register('clutter')
31 class ClutterInputHook(InputHookBase):
32 def enable(self, app=None):
33 self.manager.set_inputhook(inputhook_clutter)
34
35 You can also optionally define a ``disable()`` method, taking no arguments, if
36 there are extra steps needed to clean up. IPython will take care of resetting
37 the hook, whether or not you provide a disable method.
38
39 The simplest way to define the hook function is just to run one iteration of the
40 event loop, or to run until no events are pending. Most event loops provide some
41 mechanism to do one of these things. However, the GUI may lag slightly,
42 because the hook is only called every 0.1 seconds. Alternatively, the hook can
43 keep running the event loop until there is input ready on stdin. IPython
44 provides a function to facilitate this:
45
46 .. currentmodule:: IPython.lib.inputhook
47
48 .. function:: stdin_ready()
49
50 Returns True if there is something ready to read on stdin.
51
52 If this is the case, the hook function should return immediately.
53
54 This is implemented for Windows and POSIX systems - on other platforms, it
55 always returns True, so that the hook always gives Python a chance to check
56 for input.
57
58
59 Event loops in the kernel
60 -------------------------
61
62 The kernel runs its own event loop, so it's simpler to integrate with others.
63 IPython allows the other event loop to take control, but it must call
64 :meth:`IPython.kernel.zmq.kernelbase.Kernel.do_one_iteration` periodically.
65
66 To integrate with this, write a function that takes a single argument,
67 the IPython kernel instance, arranges for your event loop to call
68 ``kernel.do_one_iteration()`` at least every ``kernel._poll_interval`` seconds,
69 and starts the event loop.
70
71 Decorate this function with :func:`IPython.kernel.zmq.eventloops.register_integration`,
72 passing in the names you wish to register it for. Here is a slightly simplified
73 version of the Tkinter integration already included in IPython::
74
75 @register_integration('tk')
76 def loop_tk(kernel):
77 """Start a kernel with the Tk event loop."""
78 from tkinter import Tk
79
80 # Tk uses milliseconds
81 poll_interval = int(1000*kernel._poll_interval)
82 # For Tkinter, we create a Tk object and call its withdraw method.
83 class Timer(object):
84 def __init__(self, func):
85 self.app = Tk()
86 self.app.withdraw()
87 self.func = func
88
89 def on_timer(self):
90 self.func()
91 self.app.after(poll_interval, self.on_timer)
92
93 def start(self):
94 self.on_timer() # Call it once to get things going.
95 self.app.mainloop()
96
97 kernel.timer = Timer(kernel.do_one_iteration)
98 kernel.timer.start()
99
100 Some event loops can go one better, and integrate checking for messages on the
101 kernel's ZMQ sockets, making the kernel more responsive than plain polling. How
102 to do this is outside the scope of this document; if you are interested, look at
103 the integration with Qt in :mod:`IPython.kernel.zmq.eventloops`.
@@ -0,0 +1,7 b''
1 * It's now possible to provide mechanisms to integrate IPython with other event
2 loops, in addition to the ones we already support. This lets you run GUI code
3 in IPython with an interactive prompt, and to embed the IPython
4 kernel in GUI applications. See :doc:`/config/eventloops` for details. As part
5 of this, the direct ``enable_*`` and ``disable_*`` functions for various GUIs
6 in :mod:`IPython.lib.inputhook` have been deprecated in favour of
7 :meth:`~.InputHookManager.enable_gui` and :meth:`~.InputHookManager.disable_gui`.
@@ -1,264 +1,285 b''
1 1 # encoding: utf-8
2 2 """Event loop integration for the ZeroMQ-based kernels.
3 3 """
4 4
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (C) 2011 The IPython Development Team
7 7
8 8 # Distributed under the terms of the BSD License. The full license is in
9 9 # the file COPYING, distributed as part of this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import sys
18 18
19 19 # System library imports
20 20 import zmq
21 21
22 22 # Local imports
23 23 from IPython.config.application import Application
24 24 from IPython.utils import io
25 25
26 26
27 27 #------------------------------------------------------------------------------
28 28 # Eventloops for integrating the Kernel into different GUIs
29 29 #------------------------------------------------------------------------------
30 30
31 31 def _on_os_x_10_9():
32 32 import platform
33 33 from distutils.version import LooseVersion as V
34 34 return sys.platform == 'darwin' and V(platform.mac_ver()[0]) >= V('10.9')
35 35
36 36 def _notify_stream_qt(kernel, stream):
37 37
38 38 from IPython.external.qt_for_kernel import QtCore
39 39
40 40 if _on_os_x_10_9() and kernel._darwin_app_nap:
41 41 from IPython.external.appnope import nope_scope as context
42 42 else:
43 43 from IPython.core.interactiveshell import NoOpContext as context
44 44
45 45 def process_stream_events():
46 46 while stream.getsockopt(zmq.EVENTS) & zmq.POLLIN:
47 47 with context():
48 48 kernel.do_one_iteration()
49 49
50 50 fd = stream.getsockopt(zmq.FD)
51 51 notifier = QtCore.QSocketNotifier(fd, QtCore.QSocketNotifier.Read, kernel.app)
52 52 notifier.activated.connect(process_stream_events)
53 53
54 # mapping of keys to loop functions
55 loop_map = {
56 'inline': None,
57 None : None,
58 }
59
60 def register_integration(*toolkitnames):
61 """Decorator to register an event loop to integrate with the IPython kernel
62
63 The decorator takes names to register the event loop as for the %gui magic.
64 You can provide alternative names for the same toolkit.
65
66 The decorated function should take a single argument, the IPython kernel
67 instance, arrange for the event loop to call ``kernel.do_one_iteration()``
68 at least every ``kernel._poll_interval`` seconds, and start the event loop.
69
70 :mod:`IPython.kernel.zmq.eventloops` provides and registers such functions
71 for a few common event loops.
72 """
73 def decorator(func):
74 for name in toolkitnames:
75 loop_map[name] = func
76 return func
77
78 return decorator
79
80
81 @register_integration('qt', 'qt4')
54 82 def loop_qt4(kernel):
55 83 """Start a kernel with PyQt4 event loop integration."""
56 84
57 85 from IPython.lib.guisupport import get_app_qt4, start_event_loop_qt4
58 86
59 87 kernel.app = get_app_qt4([" "])
60 88 kernel.app.setQuitOnLastWindowClosed(False)
61 89
62 90 for s in kernel.shell_streams:
63 91 _notify_stream_qt(kernel, s)
64 92
65 93 start_event_loop_qt4(kernel.app)
66 94
67 95
96 @register_integration('wx')
68 97 def loop_wx(kernel):
69 98 """Start a kernel with wx event loop support."""
70 99
71 100 import wx
72 101 from IPython.lib.guisupport import start_event_loop_wx
73 102
74 103 if _on_os_x_10_9() and kernel._darwin_app_nap:
75 104 # we don't hook up App Nap contexts for Wx,
76 105 # just disable it outright.
77 106 from IPython.external.appnope import nope
78 107 nope()
79 108
80 109 doi = kernel.do_one_iteration
81 110 # Wx uses milliseconds
82 111 poll_interval = int(1000*kernel._poll_interval)
83 112
84 113 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
85 114 # We make the Frame hidden when we create it in the main app below.
86 115 class TimerFrame(wx.Frame):
87 116 def __init__(self, func):
88 117 wx.Frame.__init__(self, None, -1)
89 118 self.timer = wx.Timer(self)
90 119 # Units for the timer are in milliseconds
91 120 self.timer.Start(poll_interval)
92 121 self.Bind(wx.EVT_TIMER, self.on_timer)
93 122 self.func = func
94 123
95 124 def on_timer(self, event):
96 125 self.func()
97 126
98 127 # We need a custom wx.App to create our Frame subclass that has the
99 128 # wx.Timer to drive the ZMQ event loop.
100 129 class IPWxApp(wx.App):
101 130 def OnInit(self):
102 131 self.frame = TimerFrame(doi)
103 132 self.frame.Show(False)
104 133 return True
105 134
106 135 # The redirect=False here makes sure that wx doesn't replace
107 136 # sys.stdout/stderr with its own classes.
108 137 kernel.app = IPWxApp(redirect=False)
109 138
110 139 # The import of wx on Linux sets the handler for signal.SIGINT
111 140 # to 0. This is a bug in wx or gtk. We fix by just setting it
112 141 # back to the Python default.
113 142 import signal
114 143 if not callable(signal.getsignal(signal.SIGINT)):
115 144 signal.signal(signal.SIGINT, signal.default_int_handler)
116 145
117 146 start_event_loop_wx(kernel.app)
118 147
119 148
149 @register_integration('tk')
120 150 def loop_tk(kernel):
121 151 """Start a kernel with the Tk event loop."""
122 152
123 153 try:
124 154 from tkinter import Tk # Py 3
125 155 except ImportError:
126 156 from Tkinter import Tk # Py 2
127 157 doi = kernel.do_one_iteration
128 158 # Tk uses milliseconds
129 159 poll_interval = int(1000*kernel._poll_interval)
130 160 # For Tkinter, we create a Tk object and call its withdraw method.
131 161 class Timer(object):
132 162 def __init__(self, func):
133 163 self.app = Tk()
134 164 self.app.withdraw()
135 165 self.func = func
136 166
137 167 def on_timer(self):
138 168 self.func()
139 169 self.app.after(poll_interval, self.on_timer)
140 170
141 171 def start(self):
142 172 self.on_timer() # Call it once to get things going.
143 173 self.app.mainloop()
144 174
145 175 kernel.timer = Timer(doi)
146 176 kernel.timer.start()
147 177
148 178
179 @register_integration('gtk')
149 180 def loop_gtk(kernel):
150 181 """Start the kernel, coordinating with the GTK event loop"""
151 182 from .gui.gtkembed import GTKEmbed
152 183
153 184 gtk_kernel = GTKEmbed(kernel)
154 185 gtk_kernel.start()
155 186
156 187
188 @register_integration('gtk3')
157 189 def loop_gtk3(kernel):
158 190 """Start the kernel, coordinating with the GTK event loop"""
159 191 from .gui.gtk3embed import GTKEmbed
160 192
161 193 gtk_kernel = GTKEmbed(kernel)
162 194 gtk_kernel.start()
163 195
164 196
197 @register_integration('osx')
165 198 def loop_cocoa(kernel):
166 199 """Start the kernel, coordinating with the Cocoa CFRunLoop event loop
167 200 via the matplotlib MacOSX backend.
168 201 """
169 202 import matplotlib
170 203 if matplotlib.__version__ < '1.1.0':
171 204 kernel.log.warn(
172 205 "MacOSX backend in matplotlib %s doesn't have a Timer, "
173 206 "falling back on Tk for CFRunLoop integration. Note that "
174 207 "even this won't work if Tk is linked against X11 instead of "
175 208 "Cocoa (e.g. EPD). To use the MacOSX backend in the kernel, "
176 209 "you must use matplotlib >= 1.1.0, or a native libtk."
177 210 )
178 211 return loop_tk(kernel)
179 212
180 213 from matplotlib.backends.backend_macosx import TimerMac, show
181 214
182 215 # scale interval for sec->ms
183 216 poll_interval = int(1000*kernel._poll_interval)
184 217
185 218 real_excepthook = sys.excepthook
186 219 def handle_int(etype, value, tb):
187 220 """don't let KeyboardInterrupts look like crashes"""
188 221 if etype is KeyboardInterrupt:
189 222 io.raw_print("KeyboardInterrupt caught in CFRunLoop")
190 223 else:
191 224 real_excepthook(etype, value, tb)
192 225
193 226 # add doi() as a Timer to the CFRunLoop
194 227 def doi():
195 228 # restore excepthook during IPython code
196 229 sys.excepthook = real_excepthook
197 230 kernel.do_one_iteration()
198 231 # and back:
199 232 sys.excepthook = handle_int
200 233
201 234 t = TimerMac(poll_interval)
202 235 t.add_callback(doi)
203 236 t.start()
204 237
205 238 # but still need a Poller for when there are no active windows,
206 239 # during which time mainloop() returns immediately
207 240 poller = zmq.Poller()
208 241 if kernel.control_stream:
209 242 poller.register(kernel.control_stream.socket, zmq.POLLIN)
210 243 for stream in kernel.shell_streams:
211 244 poller.register(stream.socket, zmq.POLLIN)
212 245
213 246 while True:
214 247 try:
215 248 # double nested try/except, to properly catch KeyboardInterrupt
216 249 # due to pyzmq Issue #130
217 250 try:
218 251 # don't let interrupts during mainloop invoke crash_handler:
219 252 sys.excepthook = handle_int
220 253 show.mainloop()
221 254 sys.excepthook = real_excepthook
222 255 # use poller if mainloop returned (no windows)
223 256 # scale by extra factor of 10, since it's a real poll
224 257 poller.poll(10*poll_interval)
225 258 kernel.do_one_iteration()
226 259 except:
227 260 raise
228 261 except KeyboardInterrupt:
229 262 # Ctrl-C shouldn't crash the kernel
230 263 io.raw_print("KeyboardInterrupt caught in kernel")
231 264 finally:
232 265 # ensure excepthook is restored
233 266 sys.excepthook = real_excepthook
234 267
235 # mapping of keys to loop functions
236 loop_map = {
237 'qt' : loop_qt4,
238 'qt4': loop_qt4,
239 'inline': None,
240 'osx': loop_cocoa,
241 'wx' : loop_wx,
242 'tk' : loop_tk,
243 'gtk': loop_gtk,
244 'gtk3': loop_gtk3,
245 None : None,
246 }
247 268
248 269
249 270 def enable_gui(gui, kernel=None):
250 271 """Enable integration with a given GUI"""
251 272 if gui not in loop_map:
252 273 e = "Invalid GUI request %r, valid ones are:%s" % (gui, loop_map.keys())
253 274 raise ValueError(e)
254 275 if kernel is None:
255 276 if Application.initialized():
256 277 kernel = getattr(Application.instance(), 'kernel', None)
257 278 if kernel is None:
258 279 raise RuntimeError("You didn't specify a kernel,"
259 280 " and no IPython Application with a kernel appears to be running."
260 281 )
261 282 loop = loop_map[gui]
262 283 if loop and kernel.eventloop is not None and kernel.eventloop is not loop:
263 284 raise RuntimeError("Cannot activate multiple GUI eventloops")
264 285 kernel.eventloop = loop
@@ -1,542 +1,569 b''
1 1 # coding: utf-8
2 2 """
3 3 Inputhook management for GUI event loop integration.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 try:
18 18 import ctypes
19 19 except ImportError:
20 20 ctypes = None
21 21 except SystemError: # IronPython issue, 2/8/2014
22 22 ctypes = None
23 23 import os
24 24 import sys
25 25 from distutils.version import LooseVersion as V
26 26
27 27 from IPython.utils.warn import warn
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Constants
31 31 #-----------------------------------------------------------------------------
32 32
33 33 # Constants for identifying the GUI toolkits.
34 34 GUI_WX = 'wx'
35 35 GUI_QT = 'qt'
36 36 GUI_QT4 = 'qt4'
37 37 GUI_GTK = 'gtk'
38 38 GUI_TK = 'tk'
39 39 GUI_OSX = 'osx'
40 40 GUI_GLUT = 'glut'
41 41 GUI_PYGLET = 'pyglet'
42 42 GUI_GTK3 = 'gtk3'
43 43 GUI_NONE = 'none' # i.e. disable
44 44
45 45 #-----------------------------------------------------------------------------
46 46 # Utilities
47 47 #-----------------------------------------------------------------------------
48 48
49 49 def _stdin_ready_posix():
50 50 """Return True if there's something to read on stdin (posix version)."""
51 51 infds, outfds, erfds = select.select([sys.stdin],[],[],0)
52 52 return bool(infds)
53 53
54 54 def _stdin_ready_nt():
55 55 """Return True if there's something to read on stdin (nt version)."""
56 56 return msvcrt.kbhit()
57 57
58 58 def _stdin_ready_other():
59 59 """Return True, assuming there's something to read on stdin."""
60 60 return True #
61 61
62 62
63 63 def _ignore_CTRL_C_posix():
64 64 """Ignore CTRL+C (SIGINT)."""
65 65 signal.signal(signal.SIGINT, signal.SIG_IGN)
66 66
67 67 def _allow_CTRL_C_posix():
68 68 """Take CTRL+C into account (SIGINT)."""
69 69 signal.signal(signal.SIGINT, signal.default_int_handler)
70 70
71 71 def _ignore_CTRL_C_other():
72 72 """Ignore CTRL+C (not implemented)."""
73 73 pass
74 74
75 75 def _allow_CTRL_C_other():
76 76 """Take CTRL+C into account (not implemented)."""
77 77 pass
78 78
79 79 if os.name == 'posix':
80 80 import select
81 81 import signal
82 82 stdin_ready = _stdin_ready_posix
83 83 ignore_CTRL_C = _ignore_CTRL_C_posix
84 84 allow_CTRL_C = _allow_CTRL_C_posix
85 85 elif os.name == 'nt':
86 86 import msvcrt
87 87 stdin_ready = _stdin_ready_nt
88 88 ignore_CTRL_C = _ignore_CTRL_C_other
89 89 allow_CTRL_C = _allow_CTRL_C_other
90 90 else:
91 91 stdin_ready = _stdin_ready_other
92 92 ignore_CTRL_C = _ignore_CTRL_C_other
93 93 allow_CTRL_C = _allow_CTRL_C_other
94 94
95 95
96 96 #-----------------------------------------------------------------------------
97 97 # Main InputHookManager class
98 98 #-----------------------------------------------------------------------------
99 99
100 100
101 101 class InputHookManager(object):
102 102 """Manage PyOS_InputHook for different GUI toolkits.
103 103
104 104 This class installs various hooks under ``PyOSInputHook`` to handle
105 105 GUI event loop integration.
106 106 """
107 107
108 108 def __init__(self):
109 109 if ctypes is None:
110 110 warn("IPython GUI event loop requires ctypes, %gui will not be available")
111 111 return
112 112 self.PYFUNC = ctypes.PYFUNCTYPE(ctypes.c_int)
113 self._apps = {}
113 self.guihooks = {}
114 self.aliases = {}
115 self.apps = {}
114 116 self._reset()
115 117
116 118 def _reset(self):
117 119 self._callback_pyfunctype = None
118 120 self._callback = None
119 121 self._installed = False
120 122 self._current_gui = None
121 123
122 124 def get_pyos_inputhook(self):
123 125 """Return the current PyOS_InputHook as a ctypes.c_void_p."""
124 126 return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
125 127
126 128 def get_pyos_inputhook_as_func(self):
127 129 """Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
128 130 return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
129 131
130 132 def set_inputhook(self, callback):
131 133 """Set PyOS_InputHook to callback and return the previous one."""
132 134 # On platforms with 'readline' support, it's all too likely to
133 135 # have a KeyboardInterrupt signal delivered *even before* an
134 136 # initial ``try:`` clause in the callback can be executed, so
135 137 # we need to disable CTRL+C in this situation.
136 138 ignore_CTRL_C()
137 139 self._callback = callback
138 140 self._callback_pyfunctype = self.PYFUNC(callback)
139 141 pyos_inputhook_ptr = self.get_pyos_inputhook()
140 142 original = self.get_pyos_inputhook_as_func()
141 143 pyos_inputhook_ptr.value = \
142 144 ctypes.cast(self._callback_pyfunctype, ctypes.c_void_p).value
143 145 self._installed = True
144 146 return original
145 147
146 148 def clear_inputhook(self, app=None):
147 149 """Set PyOS_InputHook to NULL and return the previous one.
148 150
149 151 Parameters
150 152 ----------
151 153 app : optional, ignored
152 154 This parameter is allowed only so that clear_inputhook() can be
153 155 called with a similar interface as all the ``enable_*`` methods. But
154 156 the actual value of the parameter is ignored. This uniform interface
155 157 makes it easier to have user-level entry points in the main IPython
156 158 app like :meth:`enable_gui`."""
157 159 pyos_inputhook_ptr = self.get_pyos_inputhook()
158 160 original = self.get_pyos_inputhook_as_func()
159 161 pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
160 162 allow_CTRL_C()
161 163 self._reset()
162 164 return original
163 165
164 166 def clear_app_refs(self, gui=None):
165 167 """Clear IPython's internal reference to an application instance.
166 168
167 169 Whenever we create an app for a user on qt4 or wx, we hold a
168 170 reference to the app. This is needed because in some cases bad things
169 171 can happen if a user doesn't hold a reference themselves. This
170 172 method is provided to clear the references we are holding.
171 173
172 174 Parameters
173 175 ----------
174 176 gui : None or str
175 177 If None, clear all app references. If ('wx', 'qt4') clear
176 178 the app for that toolkit. References are not held for gtk or tk
177 179 as those toolkits don't have the notion of an app.
178 180 """
179 181 if gui is None:
180 self._apps = {}
181 elif gui in self._apps:
182 del self._apps[gui]
182 self.apps = {}
183 elif gui in self.apps:
184 del self.apps[gui]
183 185
184 def enable_wx(self, app=None):
186 def register(self, toolkitname, *aliases):
187 """Register a class to provide the event loop for a given GUI.
188
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
191 themselves should subclass :class:`InputHookBase`.
192
193 ::
194
195 @inputhook_manager.register('qt')
196 class QtInputHook(InputHookBase):
197 def enable(self, app=None):
198 ...
199 """
200 def decorator(cls):
201 inst = cls(self)
202 self.guihooks[toolkitname] = inst
203 for a in aliases:
204 self.aliases[a] = toolkitname
205 return cls
206 return decorator
207
208 def current_gui(self):
209 """Return a string indicating the currently active GUI or None."""
210 return self._current_gui
211
212 def enable_gui(self, gui=None, app=None):
213 """Switch amongst GUI input hooks by name.
214
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
217 for that GUI.
218
219 Parameters
220 ----------
221 gui : optional, string or None
222 If None (or 'none'), clears input hook, otherwise it must be one
223 of the recognized GUI names (see ``GUI_*`` constants in module).
224
225 app : optional, existing application object.
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
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.
230
231 Returns
232 -------
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
235 one.
236 """
237 if gui in (None, GUI_NONE):
238 return self.disable_gui()
239
240 if gui in self.aliases:
241 return self.enable_gui(self.aliases[gui], app)
242
243 try:
244 gui_hook = self.guihooks[gui]
245 except KeyError:
246 e = "Invalid GUI request {!r}, valid ones are: {}"
247 raise ValueError(e.format(gui, ', '.join(self.guihooks)))
248 self._current_gui = gui
249 return gui_hook.enable(app)
250
251 def disable_gui(self):
252 """Disable GUI event loop integration.
253
254 If an application was registered, this sets its ``_in_event_loop``
255 attribute to False. It then calls :meth:`clear_inputhook`.
256 """
257 gui = self._current_gui
258 if gui in self.apps:
259 self.apps[gui]._in_event_loop = False
260 return self.clear_inputhook()
261
262 class InputHookBase(object):
263 """Base class for input hooks for specific toolkits.
264
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.
267 They may also define a :meth:`disable` method with no arguments.
268 """
269 def __init__(self, manager):
270 self.manager = manager
271
272 def disable(self):
273 pass
274
275 inputhook_manager = InputHookManager()
276
277 @inputhook_manager.register('wx')
278 class WxInputHook(InputHookBase):
279 def enable(self, app=None):
185 280 """Enable event loop integration with wxPython.
186 281
187 282 Parameters
188 283 ----------
189 284 app : WX Application, optional.
190 285 Running application to use. If not given, we probe WX for an
191 286 existing application object, and create a new one if none is found.
192 287
193 288 Notes
194 289 -----
195 290 This methods sets the ``PyOS_InputHook`` for wxPython, which allows
196 291 the wxPython to integrate with terminal based applications like
197 292 IPython.
198 293
199 294 If ``app`` is not given we probe for an existing one, and return it if
200 295 found. If no existing app is found, we create an :class:`wx.App` as
201 296 follows::
202 297
203 298 import wx
204 299 app = wx.App(redirect=False, clearSigInt=False)
205 300 """
206 301 import wx
207 302
208 303 wx_version = V(wx.__version__).version
209 304
210 305 if wx_version < [2, 8]:
211 306 raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__)
212 307
213 308 from IPython.lib.inputhookwx import inputhook_wx
214 309 from IPython.external.appnope import nope
215 self.set_inputhook(inputhook_wx)
310 self.manager.set_inputhook(inputhook_wx)
216 311 nope()
217 self._current_gui = GUI_WX
312
218 313 import wx
219 314 if app is None:
220 315 app = wx.GetApp()
221 316 if app is None:
222 317 app = wx.App(redirect=False, clearSigInt=False)
223 318 app._in_event_loop = True
224 self._apps[GUI_WX] = app
319 self.manager.apps[GUI_WX] = app
225 320 return app
226 321
227 def disable_wx(self):
322 def disable(self):
228 323 """Disable event loop integration with wxPython.
229 324
230 This merely sets PyOS_InputHook to NULL.
325 This restores appnapp on OS X
231 326 """
232 327 from IPython.external.appnope import nap
233 if GUI_WX in self._apps:
234 self._apps[GUI_WX]._in_event_loop = False
235 self.clear_inputhook()
236 328 nap()
237 329
238 def enable_qt4(self, app=None):
330 @inputhook_manager.register('qt', 'qt4')
331 class Qt4InputHook(InputHookBase):
332 def enable(self, app=None):
239 333 """Enable event loop integration with PyQt4.
240 334
241 335 Parameters
242 336 ----------
243 337 app : Qt Application, optional.
244 338 Running application to use. If not given, we probe Qt for an
245 339 existing application object, and create a new one if none is found.
246 340
247 341 Notes
248 342 -----
249 343 This methods sets the PyOS_InputHook for PyQt4, which allows
250 344 the PyQt4 to integrate with terminal based applications like
251 345 IPython.
252 346
253 347 If ``app`` is not given we probe for an existing one, and return it if
254 348 found. If no existing app is found, we create an :class:`QApplication`
255 349 as follows::
256 350
257 351 from PyQt4 import QtCore
258 352 app = QtGui.QApplication(sys.argv)
259 353 """
260 354 from IPython.lib.inputhookqt4 import create_inputhook_qt4
261 355 from IPython.external.appnope import nope
262 356 app, inputhook_qt4 = create_inputhook_qt4(self, app)
263 self.set_inputhook(inputhook_qt4)
357 self.manager.set_inputhook(inputhook_qt4)
264 358 nope()
265 359
266 self._current_gui = GUI_QT4
267 360 app._in_event_loop = True
268 self._apps[GUI_QT4] = app
361 self.manager.apps[GUI_QT4] = app
269 362 return app
270 363
271 364 def disable_qt4(self):
272 365 """Disable event loop integration with PyQt4.
273 366
274 This merely sets PyOS_InputHook to NULL.
367 This restores appnapp on OS X
275 368 """
276 369 from IPython.external.appnope import nap
277 if GUI_QT4 in self._apps:
278 self._apps[GUI_QT4]._in_event_loop = False
279 self.clear_inputhook()
280 370 nap()
281 371
282 def enable_gtk(self, app=None):
372 @inputhook_manager.register('gtk')
373 class GtkInputHook(InputHookBase):
374 def enable(self, app=None):
283 375 """Enable event loop integration with PyGTK.
284 376
285 377 Parameters
286 378 ----------
287 379 app : ignored
288 380 Ignored, it's only a placeholder to keep the call signature of all
289 381 gui activation methods consistent, which simplifies the logic of
290 382 supporting magics.
291 383
292 384 Notes
293 385 -----
294 386 This methods sets the PyOS_InputHook for PyGTK, which allows
295 387 the PyGTK to integrate with terminal based applications like
296 388 IPython.
297 389 """
298 390 import gtk
299 391 try:
300 392 gtk.set_interactive(True)
301 self._current_gui = GUI_GTK
302 393 except AttributeError:
303 394 # For older versions of gtk, use our own ctypes version
304 395 from IPython.lib.inputhookgtk import inputhook_gtk
305 self.set_inputhook(inputhook_gtk)
306 self._current_gui = GUI_GTK
396 self.manager.set_inputhook(inputhook_gtk)
307 397
308 def disable_gtk(self):
309 """Disable event loop integration with PyGTK.
310
311 This merely sets PyOS_InputHook to NULL.
312 """
313 self.clear_inputhook()
314 398
315 def enable_tk(self, app=None):
399 @inputhook_manager.register('tk')
400 class TkInputHook(InputHookBase):
401 def enable(self, app=None):
316 402 """Enable event loop integration with Tk.
317 403
318 404 Parameters
319 405 ----------
320 406 app : toplevel :class:`Tkinter.Tk` widget, optional.
321 407 Running toplevel widget to use. If not given, we probe Tk for an
322 408 existing one, and create a new one if none is found.
323 409
324 410 Notes
325 411 -----
326 412 If you have already created a :class:`Tkinter.Tk` object, the only
327 413 thing done by this method is to register with the
328 414 :class:`InputHookManager`, since creating that object automatically
329 415 sets ``PyOS_InputHook``.
330 416 """
331 self._current_gui = GUI_TK
332 417 if app is None:
333 418 try:
334 419 from tkinter import Tk # Py 3
335 420 except ImportError:
336 421 from Tkinter import Tk # Py 2
337 422 app = Tk()
338 423 app.withdraw()
339 self._apps[GUI_TK] = app
424 self.manager.apps[GUI_TK] = app
340 425 return app
341 426
342 def disable_tk(self):
343 """Disable event loop integration with Tkinter.
344
345 This merely sets PyOS_InputHook to NULL.
346 """
347 self.clear_inputhook()
348
349 427
350 def enable_glut(self, app=None):
351 """ Enable event loop integration with GLUT.
428 @inputhook_manager.register('glut')
429 class GlutInputHook(InputHookBase):
430 def enable(self, app=None):
431 """Enable event loop integration with GLUT.
352 432
353 433 Parameters
354 434 ----------
355 435
356 436 app : ignored
357 437 Ignored, it's only a placeholder to keep the call signature of all
358 438 gui activation methods consistent, which simplifies the logic of
359 439 supporting magics.
360 440
361 441 Notes
362 442 -----
363 443
364 444 This methods sets the PyOS_InputHook for GLUT, which allows the GLUT to
365 445 integrate with terminal based applications like IPython. Due to GLUT
366 446 limitations, it is currently not possible to start the event loop
367 447 without first creating a window. You should thus not create another
368 448 window but use instead the created one. See 'gui-glut.py' in the
369 449 docs/examples/lib directory.
370 450
371 451 The default screen mode is set to:
372 452 glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
373 453 """
374 454
375 455 import OpenGL.GLUT as glut
376 456 from IPython.lib.inputhookglut import glut_display_mode, \
377 457 glut_close, glut_display, \
378 458 glut_idle, inputhook_glut
379 459
380 if GUI_GLUT not in self._apps:
460 if GUI_GLUT not in self.manager.apps:
381 461 glut.glutInit( sys.argv )
382 462 glut.glutInitDisplayMode( glut_display_mode )
383 463 # This is specific to freeglut
384 464 if bool(glut.glutSetOption):
385 465 glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
386 466 glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
387 467 glut.glutCreateWindow( sys.argv[0] )
388 468 glut.glutReshapeWindow( 1, 1 )
389 469 glut.glutHideWindow( )
390 470 glut.glutWMCloseFunc( glut_close )
391 471 glut.glutDisplayFunc( glut_display )
392 472 glut.glutIdleFunc( glut_idle )
393 473 else:
394 474 glut.glutWMCloseFunc( glut_close )
395 475 glut.glutDisplayFunc( glut_display )
396 476 glut.glutIdleFunc( glut_idle)
397 self.set_inputhook( inputhook_glut )
398 self._current_gui = GUI_GLUT
399 self._apps[GUI_GLUT] = True
477 self.manager.set_inputhook( inputhook_glut )
478 self.manager.apps[GUI_GLUT] = True
400 479
401 480
402 def disable_glut(self):
481 def disable(self):
403 482 """Disable event loop integration with glut.
404 483
405 484 This sets PyOS_InputHook to NULL and set the display function to a
406 485 dummy one and set the timer to a dummy timer that will be triggered
407 486 very far in the future.
408 487 """
409 488 import OpenGL.GLUT as glut
410 489 from glut_support import glutMainLoopEvent
411 490
412 491 glut.glutHideWindow() # This is an event to be processed below
413 492 glutMainLoopEvent()
414 self.clear_inputhook()
493 super(GlutInputHook, self).disable()
415 494
416 def enable_pyglet(self, app=None):
495 @inputhook_manager.register('pyglet')
496 class PygletInputHook(InputHookBase):
497 def enable(self, app=None):
417 498 """Enable event loop integration with pyglet.
418 499
419 500 Parameters
420 501 ----------
421 502 app : ignored
422 503 Ignored, it's only a placeholder to keep the call signature of all
423 504 gui activation methods consistent, which simplifies the logic of
424 505 supporting magics.
425 506
426 507 Notes
427 508 -----
428 509 This methods sets the ``PyOS_InputHook`` for pyglet, which allows
429 510 pyglet to integrate with terminal based applications like
430 511 IPython.
431 512
432 513 """
433 514 from IPython.lib.inputhookpyglet import inputhook_pyglet
434 self.set_inputhook(inputhook_pyglet)
435 self._current_gui = GUI_PYGLET
515 self.manager.set_inputhook(inputhook_pyglet)
436 516 return app
437 517
438 def disable_pyglet(self):
439 """Disable event loop integration with pyglet.
440 518
441 This merely sets PyOS_InputHook to NULL.
442 """
443 self.clear_inputhook()
444
445 def enable_gtk3(self, app=None):
519 @inputhook_manager.register('gtk3')
520 class Gtk3InputHook(InputHookBase):
521 def enable(self, app=None):
446 522 """Enable event loop integration with Gtk3 (gir bindings).
447 523
448 524 Parameters
449 525 ----------
450 526 app : ignored
451 527 Ignored, it's only a placeholder to keep the call signature of all
452 528 gui activation methods consistent, which simplifies the logic of
453 529 supporting magics.
454 530
455 531 Notes
456 532 -----
457 533 This methods sets the PyOS_InputHook for Gtk3, which allows
458 534 the Gtk3 to integrate with terminal based applications like
459 535 IPython.
460 536 """
461 537 from IPython.lib.inputhookgtk3 import inputhook_gtk3
462 self.set_inputhook(inputhook_gtk3)
463 self._current_gui = GUI_GTK
538 self.manager.set_inputhook(inputhook_gtk3)
539 self.manager._current_gui = GUI_GTK
464 540
465 def disable_gtk3(self):
466 """Disable event loop integration with PyGTK.
467 541
468 This merely sets PyOS_InputHook to NULL.
469 """
470 self.clear_inputhook()
471
472 def current_gui(self):
473 """Return a string indicating the currently active GUI or None."""
474 return self._current_gui
475
476 inputhook_manager = InputHookManager()
477
478 enable_wx = inputhook_manager.enable_wx
479 disable_wx = inputhook_manager.disable_wx
480 enable_qt4 = inputhook_manager.enable_qt4
481 disable_qt4 = inputhook_manager.disable_qt4
482 enable_gtk = inputhook_manager.enable_gtk
483 disable_gtk = inputhook_manager.disable_gtk
484 enable_tk = inputhook_manager.enable_tk
485 disable_tk = inputhook_manager.disable_tk
486 enable_glut = inputhook_manager.enable_glut
487 disable_glut = inputhook_manager.disable_glut
488 enable_pyglet = inputhook_manager.enable_pyglet
489 disable_pyglet = inputhook_manager.disable_pyglet
490 enable_gtk3 = inputhook_manager.enable_gtk3
491 disable_gtk3 = inputhook_manager.disable_gtk3
492 542 clear_inputhook = inputhook_manager.clear_inputhook
493 543 set_inputhook = inputhook_manager.set_inputhook
494 544 current_gui = inputhook_manager.current_gui
495 545 clear_app_refs = inputhook_manager.clear_app_refs
496
497 guis = {None: clear_inputhook,
498 GUI_NONE: clear_inputhook,
499 GUI_OSX: lambda app=False: None,
500 GUI_TK: enable_tk,
501 GUI_GTK: enable_gtk,
502 GUI_WX: enable_wx,
503 GUI_QT: enable_qt4, # qt3 not supported
504 GUI_QT4: enable_qt4,
505 GUI_GLUT: enable_glut,
506 GUI_PYGLET: enable_pyglet,
507 GUI_GTK3: enable_gtk3,
508 }
509
510
511 # Convenience function to switch amongst them
512 def enable_gui(gui=None, app=None):
513 """Switch amongst GUI input hooks by name.
514
515 This is just a utility wrapper around the methods of the InputHookManager
516 object.
517
518 Parameters
519 ----------
520 gui : optional, string or None
521 If None (or 'none'), clears input hook, otherwise it must be one
522 of the recognized GUI names (see ``GUI_*`` constants in module).
523
524 app : optional, existing application object.
525 For toolkits that have the concept of a global app, you can supply an
526 existing one. If not given, the toolkit will be probed for one, and if
527 none is found, a new one will be created. Note that GTK does not have
528 this concept, and passing an app if ``gui=="GTK"`` will raise an error.
529
530 Returns
531 -------
532 The output of the underlying gui switch routine, typically the actual
533 PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
534 one.
535 """
536 try:
537 gui_hook = guis[gui]
538 except KeyError:
539 e = "Invalid GUI request %r, valid ones are:%s" % (gui, guis.keys())
540 raise ValueError(e)
541 return gui_hook(app)
542
546 enable_gui = inputhook_manager.enable_gui
547 disable_gui = inputhook_manager.disable_gui
548 register = inputhook_manager.register
549 guis = inputhook_manager.guihooks
550
551 # Deprecated methods: kept for backwards compatibility, do not use in new code
552 def _make_deprecated_enable(name):
553 def enable_toolkit(app=None):
554 warn("This function is deprecated - use enable_gui(%r) instead" % name)
555 inputhook_manager.enable_gui(name, app)
556
557 enable_wx = _make_deprecated_enable('wx')
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()
568 disable_wx = disable_qt4 = disable_gtk = disable_gtk3 = disable_glut = \
569 disable_pyglet = _deprecated_disable
@@ -1,32 +1,33 b''
1 1 .. _config_index:
2 2
3 3 ===============================
4 4 Configuration and customization
5 5 ===============================
6 6
7 7 Configuring IPython
8 8 -------------------
9 9
10 10 .. toctree::
11 11 :maxdepth: 2
12 12
13 13 intro
14 14 options/index
15 15 details
16 16
17 17 .. seealso::
18 18
19 19 :doc:`/development/config`
20 20 Technical details of the config system.
21 21
22 22 Extending and integrating with IPython
23 23 --------------------------------------
24 24
25 25 .. toctree::
26 26 :maxdepth: 2
27 27
28 28 extensions/index
29 29 integrating
30 30 custommagics
31 31 inputtransforms
32 32 callbacks
33 eventloops
@@ -1,39 +1,39 b''
1 1 #!/usr/bin/env python
2 2 """Simple GTK example to manually test event loop integration.
3 3
4 4 This is meant to run tests manually in ipython as:
5 5
6 6 In [5]: %gui gtk
7 7
8 8 In [6]: %run gui-gtk.py
9 9 """
10 10
11 11 import pygtk
12 12 pygtk.require('2.0')
13 13 import gtk
14 14
15 15
16 16 def hello_world(wigdet, data=None):
17 17 print("Hello World")
18 18
19 19 def delete_event(widget, event, data=None):
20 20 return False
21 21
22 22 def destroy(widget, data=None):
23 23 gtk.main_quit()
24 24
25 25 window = gtk.Window(gtk.WINDOW_TOPLEVEL)
26 26 window.connect("delete_event", delete_event)
27 27 window.connect("destroy", destroy)
28 28 button = gtk.Button("Hello World")
29 29 button.connect("clicked", hello_world, None)
30 30
31 31 window.add(button)
32 32 button.show()
33 33 window.show()
34 34
35 35 try:
36 from IPython.lib.inputhook import enable_gtk
37 enable_gtk()
36 from IPython.lib.inputhook import enable_gui
37 enable_gui('gtk')
38 38 except ImportError:
39 39 gtk.main()
@@ -1,37 +1,37 b''
1 1 #!/usr/bin/env python
2 2 """Simple Gtk example to manually test event loop integration.
3 3
4 4 This is meant to run tests manually in ipython as:
5 5
6 6 In [1]: %gui gtk3
7 7
8 8 In [2]: %run gui-gtk3.py
9 9 """
10 10
11 11 from gi.repository import Gtk
12 12
13 13
14 14 def hello_world(wigdet, data=None):
15 15 print("Hello World")
16 16
17 17 def delete_event(widget, event, data=None):
18 18 return False
19 19
20 20 def destroy(widget, data=None):
21 21 Gtk.main_quit()
22 22
23 23 window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
24 24 window.connect("delete_event", delete_event)
25 25 window.connect("destroy", destroy)
26 26 button = Gtk.Button("Hello World")
27 27 button.connect("clicked", hello_world, None)
28 28
29 29 window.add(button)
30 30 button.show()
31 31 window.show()
32 32
33 33 try:
34 from IPython.lib.inputhook import enable_gtk3
35 enable_gtk3()
34 from IPython.lib.inputhook import enable_gui
35 enable_gui('gtk3')
36 36 except ImportError:
37 37 Gtk.main()
@@ -1,33 +1,33 b''
1 1 #!/usr/bin/env python
2 2 """Simple pyglet example to manually test event loop integration.
3 3
4 4 This is meant to run tests manually in ipython as:
5 5
6 6 In [5]: %gui pyglet
7 7
8 8 In [6]: %run gui-pyglet.py
9 9 """
10 10
11 11 import pyglet
12 12
13 13
14 14 window = pyglet.window.Window()
15 15 label = pyglet.text.Label('Hello, world',
16 16 font_name='Times New Roman',
17 17 font_size=36,
18 18 x=window.width//2, y=window.height//2,
19 19 anchor_x='center', anchor_y='center')
20 20 @window.event
21 21 def on_close():
22 22 window.close()
23 23
24 24 @window.event
25 25 def on_draw():
26 26 window.clear()
27 27 label.draw()
28 28
29 29 try:
30 from IPython.lib.inputhook import enable_pyglet
31 enable_pyglet()
30 from IPython.lib.inputhook import enable_gui
31 enable_gui('pyglet')
32 32 except ImportError:
33 33 pyglet.app.run()
@@ -1,35 +1,36 b''
1 1 #!/usr/bin/env python
2 2 """Simple Tk example to manually test event loop integration.
3 3
4 4 This is meant to run tests manually in ipython as:
5 5
6 6 In [5]: %gui tk
7 7
8 8 In [6]: %run gui-tk.py
9 9 """
10 10
11 11 try:
12 12 from tkinter import * # Python 3
13 13 except ImportError:
14 14 from Tkinter import * # Python 2
15 15
16 16 class MyApp:
17 17
18 18 def __init__(self, root):
19 19 frame = Frame(root)
20 20 frame.pack()
21 21
22 22 self.button = Button(frame, text="Hello", command=self.hello_world)
23 23 self.button.pack(side=LEFT)
24 24
25 25 def hello_world(self):
26 26 print("Hello World!")
27 27
28 28 root = Tk()
29 29
30 30 app = MyApp(root)
31 31
32 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 35 except ImportError:
35 36 root.mainloop()
@@ -1,106 +1,106 b''
1 1 #!/usr/bin/env python
2 2 """
3 3 A Simple wx example to test IPython's event loop integration.
4 4
5 5 To run this do:
6 6
7 7 In [5]: %gui wx # or start IPython with '--gui wx'
8 8
9 9 In [6]: %run gui-wx.py
10 10
11 11 Ref: Modified from wxPython source code wxPython/samples/simple/simple.py
12 12 """
13 13
14 14 import wx
15 15
16 16
17 17 class MyFrame(wx.Frame):
18 18 """
19 19 This is MyFrame. It just shows a few controls on a wxPanel,
20 20 and has a simple menu.
21 21 """
22 22 def __init__(self, parent, title):
23 23 wx.Frame.__init__(self, parent, -1, title,
24 24 pos=(150, 150), size=(350, 200))
25 25
26 26 # Create the menubar
27 27 menuBar = wx.MenuBar()
28 28
29 29 # and a menu
30 30 menu = wx.Menu()
31 31
32 32 # add an item to the menu, using \tKeyName automatically
33 33 # creates an accelerator, the third param is some help text
34 34 # that will show up in the statusbar
35 35 menu.Append(wx.ID_EXIT, "E&xit\tAlt-X", "Exit this simple sample")
36 36
37 37 # bind the menu event to an event handler
38 38 self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=wx.ID_EXIT)
39 39
40 40 # and put the menu on the menubar
41 41 menuBar.Append(menu, "&File")
42 42 self.SetMenuBar(menuBar)
43 43
44 44 self.CreateStatusBar()
45 45
46 46 # Now create the Panel to put the other controls on.
47 47 panel = wx.Panel(self)
48 48
49 49 # and a few controls
50 50 text = wx.StaticText(panel, -1, "Hello World!")
51 51 text.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD))
52 52 text.SetSize(text.GetBestSize())
53 53 btn = wx.Button(panel, -1, "Close")
54 54 funbtn = wx.Button(panel, -1, "Just for fun...")
55 55
56 56 # bind the button events to handlers
57 57 self.Bind(wx.EVT_BUTTON, self.OnTimeToClose, btn)
58 58 self.Bind(wx.EVT_BUTTON, self.OnFunButton, funbtn)
59 59
60 60 # Use a sizer to layout the controls, stacked vertically and with
61 61 # a 10 pixel border around each
62 62 sizer = wx.BoxSizer(wx.VERTICAL)
63 63 sizer.Add(text, 0, wx.ALL, 10)
64 64 sizer.Add(btn, 0, wx.ALL, 10)
65 65 sizer.Add(funbtn, 0, wx.ALL, 10)
66 66 panel.SetSizer(sizer)
67 67 panel.Layout()
68 68
69 69
70 70 def OnTimeToClose(self, evt):
71 71 """Event handler for the button click."""
72 72 print("See ya later!")
73 73 self.Close()
74 74
75 75 def OnFunButton(self, evt):
76 76 """Event handler for the button click."""
77 77 print("Having fun yet?")
78 78
79 79
80 80 class MyApp(wx.App):
81 81 def OnInit(self):
82 82 frame = MyFrame(None, "Simple wxPython App")
83 83 self.SetTopWindow(frame)
84 84
85 85 print("Print statements go to this stdout window by default.")
86 86
87 87 frame.Show(True)
88 88 return True
89 89
90 90
91 91 if __name__ == '__main__':
92 92
93 93 app = wx.GetApp()
94 94 if app is None:
95 95 app = MyApp(redirect=False, clearSigInt=False)
96 96 else:
97 97 frame = MyFrame(None, "Simple wxPython App")
98 98 app.SetTopWindow(frame)
99 99 print("Print statements go to this stdout window by default.")
100 100 frame.Show(True)
101 101
102 102 try:
103 from IPython.lib.inputhook import enable_wx
104 enable_wx(app)
103 from IPython.lib.inputhook import enable_gui
104 enable_gui('wx', app)
105 105 except ImportError:
106 106 app.MainLoop()
General Comments 0
You need to be logged in to leave comments. Login now