or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

communication-framework.mdconnection-management.mdcore-kernel.mddata-utilities.mdgui-integration.mdin-process-kernels.mdindex.mdio-streaming.mdkernel-application.mdkernel-embedding.mdmatplotlib-integration.md

gui-integration.mddocs/

0

# GUI Integration and Event Loops

1

2

Integration with GUI toolkits (Qt, Tkinter, GTK, etc.) enabling matplotlib and other GUI libraries to work seamlessly within Jupyter environments. Provides event loop management and coordination between GUI frameworks and the kernel's execution model.

3

4

## Capabilities

5

6

### GUI Enable Function

7

8

Primary function for enabling GUI toolkit integration in the kernel.

9

10

```python { .api }

11

def enable_gui(gui=None):

12

"""

13

Enable GUI event loop integration for the specified toolkit.

14

15

Enables interactive use of GUI libraries like matplotlib, Qt widgets,

16

and other GUI frameworks within Jupyter environments.

17

18

Parameters:

19

- gui (str, optional): GUI toolkit to enable

20

Options: 'qt4', 'qt5', 'qt', 'gtk', 'gtk3',

21

'wx', 'tk', 'cocoa', 'asyncio', 'osx'

22

If None, tries to auto-detect

23

24

Returns:

25

None

26

27

Raises:

28

ImportError: If specified GUI toolkit is not available

29

ValueError: If gui parameter is invalid

30

"""

31

```

32

33

### Integration Registration

34

35

Decorator and function for registering custom GUI integrations.

36

37

```python { .api }

38

def register_integration(gui):

39

"""

40

Decorator for registering GUI integration functions.

41

42

Used to register custom event loop integration functions

43

for specific GUI toolkits.

44

45

Parameters:

46

- gui (str): Name of the GUI toolkit

47

48

Returns:

49

function: Decorator function

50

51

Example:

52

@register_integration('custom_gui')

53

def loop_custom_gui(kernel):

54

# Custom integration logic

55

pass

56

"""

57

```

58

59

### Qt Integration

60

61

Functions for Qt4 and Qt5 event loop integration.

62

63

```python { .api }

64

def loop_qt4(kernel):

65

"""

66

Start Qt4 event loop integration.

67

68

Parameters:

69

- kernel: Kernel instance for integration

70

"""

71

72

def loop_qt5(kernel):

73

"""

74

Start Qt5 event loop integration.

75

76

Parameters:

77

- kernel: Kernel instance for integration

78

"""

79

```

80

81

### GTK Integration

82

83

Functions for GTK2 and GTK3 event loop integration.

84

85

```python { .api }

86

def loop_gtk(kernel):

87

"""

88

Start GTK2 event loop integration.

89

90

Parameters:

91

- kernel: Kernel instance for integration

92

"""

93

94

def loop_gtk3(kernel):

95

"""

96

Start GTK3 event loop integration.

97

98

Parameters:

99

- kernel: Kernel instance for integration

100

"""

101

```

102

103

### Other GUI Toolkit Integration

104

105

Functions for additional GUI framework support.

106

107

```python { .api }

108

def loop_wx(kernel):

109

"""

110

Start wxPython event loop integration.

111

112

Parameters:

113

- kernel: Kernel instance for integration

114

"""

115

116

def loop_tk(kernel):

117

"""

118

Start Tkinter event loop integration.

119

120

Parameters:

121

- kernel: Kernel instance for integration

122

"""

123

124

def loop_cocoa(kernel):

125

"""

126

Start Cocoa event loop integration (macOS).

127

128

Parameters:

129

- kernel: Kernel instance for integration

130

"""

131

132

def loop_asyncio(kernel):

133

"""

134

Start asyncio event loop integration.

135

136

Parameters:

137

- kernel: Kernel instance for integration

138

"""

139

```

140

141

## Usage Examples

142

143

### Basic GUI Integration

144

145

```python

146

from ipykernel.eventloops import enable_gui

147

148

# Enable Qt5 for matplotlib and other Qt applications

149

enable_gui('qt5')

150

151

# Now matplotlib plots will be interactive

152

import matplotlib.pyplot as plt

153

plt.ion() # Enable interactive mode

154

155

# Create interactive plot

156

fig, ax = plt.subplots()

157

ax.plot([1, 2, 3, 4], [1, 4, 2, 3])

158

plt.show() # Window stays responsive

159

```

160

161

### Auto-Detection of GUI Backend

162

163

```python

164

from ipykernel.eventloops import enable_gui

165

166

# Let ipykernel detect the best available GUI toolkit

167

enable_gui()

168

169

# Use GUI libraries normally

170

import matplotlib.pyplot as plt

171

plt.plot([1, 2, 3], [1, 4, 2])

172

plt.show()

173

```

174

175

### Qt Application Integration

176

177

```python

178

from ipykernel.eventloops import enable_gui

179

180

# Enable Qt5 integration

181

enable_gui('qt5')

182

183

# Now you can create Qt widgets interactively

184

try:

185

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout

186

187

app = QApplication.instance() or QApplication([])

188

189

# Create a simple Qt widget

190

widget = QWidget()

191

widget.setWindowTitle('Interactive Qt Widget')

192

193

layout = QVBoxLayout()

194

button = QPushButton('Click me!')

195

button.clicked.connect(lambda: print('Button clicked!'))

196

layout.addWidget(button)

197

198

widget.setLayout(layout)

199

widget.show()

200

201

print("Qt widget created and shown")

202

203

except ImportError:

204

print("PyQt5 not available")

205

```

206

207

### Tkinter Integration

208

209

```python

210

from ipykernel.eventloops import enable_gui

211

import tkinter as tk

212

213

# Enable Tkinter integration

214

enable_gui('tk')

215

216

# Create Tkinter application

217

root = tk.Tk()

218

root.title('Interactive Tkinter App')

219

220

# Add widgets

221

label = tk.Label(root, text='Hello from Tkinter!')

222

label.pack(pady=10)

223

224

button = tk.Button(root, text='Print Message',

225

command=lambda: print('Tkinter button pressed!'))

226

button.pack(pady=5)

227

228

# Show window - will remain responsive

229

root.mainloop()

230

```

231

232

### matplotlib with Different Backends

233

234

```python

235

from ipykernel.eventloops import enable_gui

236

import matplotlib

237

import matplotlib.pyplot as plt

238

239

# Try different GUI backends

240

gui_backends = [

241

('qt5', 'Qt5Agg'),

242

('tk', 'TkAgg'),

243

('gtk3', 'Gtk3Agg')

244

]

245

246

for gui, backend in gui_backends:

247

try:

248

# Set matplotlib backend

249

matplotlib.use(backend)

250

251

# Enable GUI integration

252

enable_gui(gui)

253

254

# Create plot

255

plt.figure(figsize=(6, 4))

256

plt.plot([1, 2, 3, 4], [1, 4, 2, 3], 'o-')

257

plt.title(f'Interactive plot with {backend}')

258

plt.show()

259

260

print(f"Successfully enabled {gui} with {backend}")

261

break

262

263

except (ImportError, ValueError) as e:

264

print(f"Failed to enable {gui}: {e}")

265

continue

266

```

267

268

### Custom GUI Integration

269

270

```python

271

from ipykernel.eventloops import register_integration, enable_gui

272

273

@register_integration('custom')

274

def loop_custom(kernel):

275

"""Custom GUI integration example."""

276

print("Starting custom GUI integration")

277

278

# Custom event loop logic here

279

# This would typically involve:

280

# 1. Setting up the GUI toolkit's event loop

281

# 2. Integrating with kernel's execution model

282

# 3. Handling GUI events without blocking kernel

283

284

def custom_event_handler():

285

# Handle custom GUI events

286

print("Custom GUI event processed")

287

288

# Register event handler with kernel

289

# (Implementation depends on specific GUI toolkit)

290

291

print("Custom GUI integration active")

292

293

# Enable custom integration

294

enable_gui('custom')

295

```

296

297

### Conditional GUI Enablement

298

299

```python

300

from ipykernel.eventloops import enable_gui

301

import sys

302

303

def setup_gui_for_platform():

304

"""Enable appropriate GUI for current platform."""

305

306

if sys.platform == 'darwin': # macOS

307

try:

308

enable_gui('cocoa')

309

print("Enabled Cocoa GUI for macOS")

310

except:

311

try:

312

enable_gui('qt5')

313

print("Enabled Qt5 GUI as fallback")

314

except:

315

print("No GUI backend available")

316

317

elif sys.platform == 'win32': # Windows

318

try:

319

enable_gui('qt5')

320

print("Enabled Qt5 GUI for Windows")

321

except:

322

try:

323

enable_gui('tk')

324

print("Enabled Tkinter GUI as fallback")

325

except:

326

print("No GUI backend available")

327

328

else: # Linux and others

329

gui_options = ['qt5', 'gtk3', 'tk']

330

for gui in gui_options:

331

try:

332

enable_gui(gui)

333

print(f"Enabled {gui} GUI for Linux")

334

break

335

except:

336

continue

337

else:

338

print("No GUI backend available")

339

340

# Setup GUI for current platform

341

setup_gui_for_platform()

342

```

343

344

### GUI with matplotlib Animation

345

346

```python

347

from ipykernel.eventloops import enable_gui

348

import matplotlib.pyplot as plt

349

import matplotlib.animation as animation

350

import numpy as np

351

352

# Enable GUI for interactive plots

353

enable_gui('qt5')

354

355

# Create animated plot

356

fig, ax = plt.subplots()

357

x = np.linspace(0, 2*np.pi, 100)

358

line, = ax.plot(x, np.sin(x))

359

360

def animate(frame):

361

"""Animation function."""

362

line.set_ydata(np.sin(x + frame/10.0))

363

return line,

364

365

# Create animation

366

anim = animation.FuncAnimation(fig, animate, frames=200,

367

interval=50, blit=True, repeat=True)

368

369

plt.title('Animated Sine Wave')

370

plt.show()

371

372

print("Animation running - window should remain responsive")

373

```