TCanvas in python function is not displayed

Hi guys,

Im trying to define a python function that creates a TGraph and displays the plot. Calling the function and exporting the TCanvas to *.eps works just fine. However, the window that usually displays the TCanvas closes instantly after opening.

[code]from ROOT import TGraph,TCanvas
from array import array

def fun():
x=array(“f”,[1,2,3,4])
y=array(“f”,[1,2,3,4])

c1=TCanvas("c1","c1",600,600)
g=TGraph(len(x),x,y)
g.Draw("A*")
c1.Print("a.eps")

fun()
[/code]

If I dont use a function and instead execute my code directly, it works just fine.

Any ideas how to solve this would be greatly appreciated!

Hi,

Python uses reference counts to manage memory, so the canvas gets collected the moment the last reference to it goes out of scope, i.e. on return of the function. You need to keep the canvas and graph alive, e.g. by assigning the graph to the canvas and returning the canvas from the function:def fun(): ... c1.g = g ... return c1 c1 = fun()
Cheers,
Wim

Thanks for answering so quickly, this works great!