0

I am writing a python program using the Networkx Viewer library. The goal of the program is to plot a graph (i.e., a set of nodes connected by vertices), and have this graph `grow' over time (i.e., new nodes emerge over time). I have written the following piece of code, based on a similar working example I took from here.

I've been trying to figure this out for the last 24 hours and am still unable to get it to work. The issue seems to be with the after method. If I remove the corresponding line, the program spits out a canvas display; otherwise, it doesn't display anything. Does anyone know how I can get this to work?

import tkinter as tk
import networkx as nx
from networkx_viewer import GraphCanvas


class GraphGrower(tk.Tk):
def __init__(self, graph):
    tk.Tk.__init__(self)
    self.graph_item = graph
    self.canvas = GraphCanvas(self.graph_item)
    self.canvas.grid(row=0, column=0, sticky='NESW')

def add_node_after(self,node_num):
    self.graph_item.add_node(node_num)
    self.canvas = GraphCanvas(self.graph_item)
    self.canvas.grid(row=0, column=0, sticky='NESW')
    self.canvas.after(10000, self.add_node_after(str(int(node_num)+1))) 
# REMOVE THE ABOVE LINE AND IT UPDATES THE GRAPH TO A 5 VERTEX GRAPH


# Graphs can be found at
# https://networkx.github.io/documentation/networkx-1.10/reference/generators.html
G = nx.fast_gnp_random_graph(4,0.85)

app = GraphGrower(G)
app.add_node_after(str(5))

app.mainloop()
Community
  • 1
  • 1
Dave S
  • 137
  • 7

1 Answers1

0

You are using after incorrectly. Consider this line of code:

self.canvas.after(10000, self.add_node_after(str(int(node_num)+1))) 

It is exactly the same as this:

result = self.add_node_after(str(int(node_num)+1))
self.canvas.after(10000, result)

See the problem? after requires a callable -- a reference to the function. If you need to pass parameters, you can add the parameters as arguments to after:

node = str(int(node_num)+1)
self.canvas.after(10000, self.add_node_after, node)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685