Is there any way to display and interact with a graph made using Networkx in Pygame?

I’m a beginner in Pygame and I’ve been trying to create a game called “Aadu Puli Aatam” for which we need to create a graph as a board, I’d like to know if there is any way to create a graph using Networkx and make it interactive using Pygame.
Whenever I try to create a graph and try to display on the screen using pygame the window stops and goes white.

The code I’ve been using:

import networkx as nx
import pygame
import sys

# Create a simple 2-node graph
G = nx.Graph()
G.add_nodes_from([1, 2])
G.add_edge(1, 2)

# Set up Pygame
pygame.init()

# Set up the screen
width, height = 400, 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("NetworkX Graph with Pygame")

# Set up colors
white = (255, 255, 255)
black = (0, 0, 0)

# Set up node positions
pos = {1: (width // 4, height // 2), 2: (3 * width // 4, height // 2)}

# Main loop
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Draw the graph
    screen.fill(white)
    nx.draw(G, pos, with_labels=True, node_size=500, node_color="skyblue", font_color=black)
    
    # Update the display
    pygame.display.update()

# Quit Pygame
pygame.quit()
sys.exit()

I tried to blit() (using pygame) it on the screen and seperately use matplotlib to show the graph (without using pygame) but it doesn’t lead to an interactive game that I’m trying to make.

Leave a Comment