CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-ipykernel

IPython Kernel for Jupyter - provides the core communication layer between Jupyter frontends and the Python interpreter

Pending
Overview
Eval results
Files

gui-integration.mddocs/

GUI Integration and Event Loops

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.

Capabilities

GUI Enable Function

Primary function for enabling GUI toolkit integration in the kernel.

def enable_gui(gui=None):
    """
    Enable GUI event loop integration for the specified toolkit.
    
    Enables interactive use of GUI libraries like matplotlib, Qt widgets,
    and other GUI frameworks within Jupyter environments.
    
    Parameters:
    - gui (str, optional): GUI toolkit to enable
                          Options: 'qt4', 'qt5', 'qt', 'gtk', 'gtk3', 
                                  'wx', 'tk', 'cocoa', 'asyncio', 'osx'
                          If None, tries to auto-detect
    
    Returns:
    None
    
    Raises:
    ImportError: If specified GUI toolkit is not available
    ValueError: If gui parameter is invalid
    """

Integration Registration

Decorator and function for registering custom GUI integrations.

def register_integration(gui):
    """
    Decorator for registering GUI integration functions.
    
    Used to register custom event loop integration functions
    for specific GUI toolkits.
    
    Parameters:
    - gui (str): Name of the GUI toolkit
    
    Returns:
    function: Decorator function
    
    Example:
    @register_integration('custom_gui')
    def loop_custom_gui(kernel):
        # Custom integration logic
        pass
    """

Qt Integration

Functions for Qt4 and Qt5 event loop integration.

def loop_qt4(kernel):
    """
    Start Qt4 event loop integration.
    
    Parameters:
    - kernel: Kernel instance for integration
    """

def loop_qt5(kernel):
    """
    Start Qt5 event loop integration.
    
    Parameters:
    - kernel: Kernel instance for integration
    """

GTK Integration

Functions for GTK2 and GTK3 event loop integration.

def loop_gtk(kernel):
    """
    Start GTK2 event loop integration.
    
    Parameters:
    - kernel: Kernel instance for integration
    """

def loop_gtk3(kernel):
    """
    Start GTK3 event loop integration.
    
    Parameters:
    - kernel: Kernel instance for integration
    """

Other GUI Toolkit Integration

Functions for additional GUI framework support.

def loop_wx(kernel):
    """
    Start wxPython event loop integration.
    
    Parameters:
    - kernel: Kernel instance for integration
    """

def loop_tk(kernel):
    """
    Start Tkinter event loop integration.
    
    Parameters:
    - kernel: Kernel instance for integration
    """

def loop_cocoa(kernel):
    """
    Start Cocoa event loop integration (macOS).
    
    Parameters:
    - kernel: Kernel instance for integration
    """

def loop_asyncio(kernel):
    """
    Start asyncio event loop integration.
    
    Parameters:
    - kernel: Kernel instance for integration
    """

Usage Examples

Basic GUI Integration

from ipykernel.eventloops import enable_gui

# Enable Qt5 for matplotlib and other Qt applications
enable_gui('qt5')

# Now matplotlib plots will be interactive
import matplotlib.pyplot as plt
plt.ion()  # Enable interactive mode

# Create interactive plot
fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.show()  # Window stays responsive

Auto-Detection of GUI Backend

from ipykernel.eventloops import enable_gui

# Let ipykernel detect the best available GUI toolkit
enable_gui()

# Use GUI libraries normally
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [1, 4, 2])
plt.show()

Qt Application Integration

from ipykernel.eventloops import enable_gui

# Enable Qt5 integration
enable_gui('qt5')

# Now you can create Qt widgets interactively
try:
    from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
    
    app = QApplication.instance() or QApplication([])
    
    # Create a simple Qt widget
    widget = QWidget()
    widget.setWindowTitle('Interactive Qt Widget')
    
    layout = QVBoxLayout()
    button = QPushButton('Click me!')
    button.clicked.connect(lambda: print('Button clicked!'))
    layout.addWidget(button)
    
    widget.setLayout(layout)
    widget.show()
    
    print("Qt widget created and shown")
    
except ImportError:
    print("PyQt5 not available")

Tkinter Integration

from ipykernel.eventloops import enable_gui
import tkinter as tk

# Enable Tkinter integration
enable_gui('tk')

# Create Tkinter application
root = tk.Tk()
root.title('Interactive Tkinter App')

# Add widgets
label = tk.Label(root, text='Hello from Tkinter!')
label.pack(pady=10)

button = tk.Button(root, text='Print Message', 
                  command=lambda: print('Tkinter button pressed!'))
button.pack(pady=5)

# Show window - will remain responsive
root.mainloop()

matplotlib with Different Backends

from ipykernel.eventloops import enable_gui
import matplotlib
import matplotlib.pyplot as plt

# Try different GUI backends
gui_backends = [
    ('qt5', 'Qt5Agg'),
    ('tk', 'TkAgg'),
    ('gtk3', 'Gtk3Agg')
]

for gui, backend in gui_backends:
    try:
        # Set matplotlib backend
        matplotlib.use(backend)
        
        # Enable GUI integration
        enable_gui(gui)
        
        # Create plot
        plt.figure(figsize=(6, 4))
        plt.plot([1, 2, 3, 4], [1, 4, 2, 3], 'o-')
        plt.title(f'Interactive plot with {backend}')
        plt.show()
        
        print(f"Successfully enabled {gui} with {backend}")
        break
        
    except (ImportError, ValueError) as e:
        print(f"Failed to enable {gui}: {e}")
        continue

Custom GUI Integration

from ipykernel.eventloops import register_integration, enable_gui

@register_integration('custom')
def loop_custom(kernel):
    """Custom GUI integration example."""
    print("Starting custom GUI integration")
    
    # Custom event loop logic here
    # This would typically involve:
    # 1. Setting up the GUI toolkit's event loop
    # 2. Integrating with kernel's execution model
    # 3. Handling GUI events without blocking kernel
    
    def custom_event_handler():
        # Handle custom GUI events
        print("Custom GUI event processed")
    
    # Register event handler with kernel
    # (Implementation depends on specific GUI toolkit)
    
    print("Custom GUI integration active")

# Enable custom integration
enable_gui('custom')

Conditional GUI Enablement

from ipykernel.eventloops import enable_gui
import sys

def setup_gui_for_platform():
    """Enable appropriate GUI for current platform."""
    
    if sys.platform == 'darwin':  # macOS
        try:
            enable_gui('cocoa')
            print("Enabled Cocoa GUI for macOS")
        except:
            try:
                enable_gui('qt5')
                print("Enabled Qt5 GUI as fallback")
            except:
                print("No GUI backend available")
                
    elif sys.platform == 'win32':  # Windows
        try:
            enable_gui('qt5')
            print("Enabled Qt5 GUI for Windows")
        except:
            try:
                enable_gui('tk')
                print("Enabled Tkinter GUI as fallback")
            except:
                print("No GUI backend available")
                
    else:  # Linux and others
        gui_options = ['qt5', 'gtk3', 'tk']
        for gui in gui_options:
            try:
                enable_gui(gui)
                print(f"Enabled {gui} GUI for Linux")
                break
            except:
                continue
        else:
            print("No GUI backend available")

# Setup GUI for current platform
setup_gui_for_platform()

GUI with matplotlib Animation

from ipykernel.eventloops import enable_gui
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

# Enable GUI for interactive plots
enable_gui('qt5')

# Create animated plot
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi, 100)
line, = ax.plot(x, np.sin(x))

def animate(frame):
    """Animation function."""
    line.set_ydata(np.sin(x + frame/10.0))
    return line,

# Create animation
anim = animation.FuncAnimation(fig, animate, frames=200, 
                             interval=50, blit=True, repeat=True)

plt.title('Animated Sine Wave')
plt.show()

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

Install with Tessl CLI

npx tessl i tessl/pypi-ipykernel

docs

communication-framework.md

connection-management.md

core-kernel.md

data-utilities.md

gui-integration.md

in-process-kernels.md

index.md

io-streaming.md

kernel-application.md

kernel-embedding.md

matplotlib-integration.md

tile.json