Create a graph in a TKinter window?

4.6k views Asked by At

I'm working on writing a script that will run through data and create a graph. That is easy and done. Unfortunately the graphing modules I am using only create the graphs in a pdf format. I would like to have the graphs displayed in an interactive window, though.

Is their any way to either add a graph created with PyX into a TKinter window or load the pdf into a frame or something?

1

There are 1 answers

0
wobsta On BEST ANSWER

You need to convert the PyX output into a bitmap to include it in your Tkinter application. While there is no convenience method to get the PyX output as a PIL image directly, you can use the pipeGS method to prepare the bitmap and load it using the PIL. Here comes a rather minimal example:

import tempfile, os

from pyx import *
import Tkinter
import Image, ImageTk

# first we create some pyx graphics
c = canvas.canvas()
c.text(0, 0, "Hello, world!")
c.stroke(path.line(0, 0, 2, 0))

# now we use pipeGS (ghostscript) to create a bitmap graphics
fd, fname = tempfile.mkstemp()
f = os.fdopen(fd, "wb")
f.close()
c.pipeGS(fname, device="pngalpha", resolution=100)
# and load with PIL
i = Image.open(fname)
i.load()
# now we can already remove the temporary file
os.unlink(fname)

# finally we can use this image in Tkinter
root = Tkinter.Tk()
root.geometry('%dx%d' % (i.size[0],i.size[1]))
tkpi = ImageTk.PhotoImage(i)
label_image = Tkinter.Label(root, image=tkpi)
label_image.place(x=0,y=0,width=i.size[0],height=i.size[1])
root.mainloop()