You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows环境手动绘制图拓扑并导入NetworkX创建Graph对象?

Great question! Parsing Inkscape XML definitely feels clunky for this use case—here are a few way smoother workflows tailored for Windows that let you draw your topology visually and convert it straight to a NetworkX Graph:

1. PyVis: Interactive Browser-Based Drawing + Direct NetworkX Import

PyVis lets you build and edit graphs interactively in your browser, and it plays nicely with NetworkX. Perfect for quick topology sketches:

  • Step 1: Install PyVis
    Open Command Prompt and run:

    pip install pyvis
    
  • Step 2: Launch an interactive graph editor
    Run this minimal script to open a browser window where you can drag nodes, click to add edges, and adjust the layout:

    from pyvis.network import Network
    
    # Initialize an interactive network
    net = Network(notebook=False, height="750px", width="100%")
    # Add a few starter nodes (you can add more in the browser)
    net.add_node("Node 1")
    net.add_node("Node 2")
    
    # Save the interactive graph to an HTML file and open it
    net.show("topology_editor.html")
    

    In the browser, use the toolbar to add nodes/edges, drag them into position, and tweak styling.

  • Step 3: Export to NetworkX
    Once you're happy with your topology, use PyVis's built-in methods to convert directly to a NetworkX Graph:

    # Load the saved PyVis network (or use the existing `net` object if you kept the script running)
    nx_graph = net.to_networkx()
    
    # Verify it works
    print("Nodes:", nx_graph.nodes())
    print("Edges:", nx_graph.edges())
    

    You can also save the PyVis graph as a JSON file and reload it later if you need to edit again:

    net.write_json("topology.json")
    # Reload later
    net = Network()
    net.read_json("topology.json")
    nx_graph = net.to_networkx()
    
2. Graphviz + PyGraphviz: Desktop-Based Visual Editor

Graphviz has a Windows desktop tool called GVEdit that lets you draw graphs visually, and NetworkX can import the .dot files it exports directly.

  • Step 1: Install Graphviz and PyGraphviz

    1. Download the Windows installer from the Graphviz official site (pick the stable release for your architecture)
    2. Add Graphviz's bin folder (e.g., C:\Program Files\Graphviz\bin) to your Windows PATH
    3. Install PyGraphviz via pip:
      pip install pygraphviz
      
  • Step 2: Draw your topology in GVEdit
    Open GVEdit (search for it in the Start Menu). Use the toolbar to add nodes, draw edges between them, and arrange the layout. When done, save the file as a .dot file (e.g., topology.dot).

  • Step 3: Import into NetworkX
    Use NetworkX's read_dot function to load the .dot file directly:

    import networkx as nx
    
    nx_graph = nx.read_dot("topology.dot")
    
    # Convert node labels to strings if needed (they might come in as bytes)
    nx_graph = nx.relabel_nodes(nx_graph, lambda x: x.decode("utf-8") if isinstance(x, bytes) else x)
    
    print("Nodes:", nx_graph.nodes())
    print("Edges:", nx_graph.edges())
    
3. Custom Tkinter GUI: Lightweight, No External Tools

If you want a fully self-contained solution (no browser or external editors), use Tkinter (included with Python on Windows) to build a simple drawing tool that outputs a NetworkX Graph directly.

Here's a minimal working example:

import tkinter as tk
import networkx as nx

class TopologyDrawer:
    def __init__(self, root):
        self.root = root
        self.root.title("Topology Drawer")
        self.canvas = tk.Canvas(root, width=800, height=600, bg="white")
        self.canvas.pack()

        self.nx_graph = nx.Graph()
        self.nodes = {}  # Maps canvas IDs to node names
        self.selected_node = None

        # Bind mouse events
        self.canvas.bind("<Button-1>", self.add_node)
        self.canvas.bind("<Button-3>", self.start_edge)
        self.canvas.bind("<ButtonRelease-3>", self.end_edge)

        # Button to export NetworkX Graph
        self.export_btn = tk.Button(root, text="Export to NetworkX", command=self.export_graph)
        self.export_btn.pack()

    def add_node(self, event):
        node_name = f"Node {len(self.nodes)+1}"
        # Draw circle on canvas
        node_id = self.canvas.create_oval(event.x-15, event.y-15, event.x+15, event.y+15, fill="lightblue")
        self.canvas.create_text(event.x, event.y, text=node_name)
        # Add to NetworkX Graph
        self.nx_graph.add_node(node_name)
        self.nodes[node_id] = node_name

    def start_edge(self, event):
        # Find which node was right-clicked
        items = self.canvas.find_closest(event.x, event.y)
        if items:
            node_id = items[0]
            if node_id in self.nodes:
                self.selected_node = self.nodes[node_id]

    def end_edge(self, event):
        if self.selected_node:
            items = self.canvas.find_closest(event.x, event.y)
            if items:
                node_id = items[0]
                if node_id in self.nodes and self.nodes[node_id] != self.selected_node:
                    target_node = self.nodes[node_id]
                    # Add edge to NetworkX Graph
                    self.nx_graph.add_edge(self.selected_node, target_node)
                    # Draw edge on canvas
                    self.canvas.create_line(
                        self.canvas.coords(node_id)[0]+15,
                        self.canvas.coords(node_id)[1]+15,
                        self.canvas.coords([k for k, v in self.nodes.items() if v == self.selected_node][0])[0]+15,
                        self.canvas.coords([k for k, v in self.nodes.items() if v == self.selected_node][0])[1]+15,
                        fill="black"
                    )
            self.selected_node = None

    def export_graph(self):
        print("Exported NetworkX Graph:")
        print("Nodes:", self.nx_graph.nodes())
        print("Edges:", self.nx_graph.edges())
        # You can also save it to a file here, e.g., nx.write_gexf(self.nx_graph, "topology.gexf")

if __name__ == "__main__":
    root = tk.Tk()
    app = TopologyDrawer(root)
    root.mainloop()

This script creates a simple window where you can:

  • Left-click to add nodes (auto-named)
  • Right-click a node, then right-click another to add an edge
  • Click "Export to NetworkX" to see the generated graph data (or extend it to save to a file)

All these methods skip the tedious XML parsing step and let you go directly from visual sketch to NetworkX object. For most use cases, PyVis is the fastest and most intuitive option on Windows, while the Tkinter approach gives you full control without any external dependencies.

内容的提问来源于stack exchange,提问作者Zubo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:09:14