2

I'm wondering how difficult it will be to use invoke matplotlib from a Tcl interpreter and plot to a Tk canvas created on the Tcl side.

I'm wondering what the best way to do this is.

I'm guessing I'll have to create a python interpreter, pass the canvas handle from the Tcl side to python and make use of the C API in both languages. Or is there a more elegant way?

nbro
  • 15,395
  • 32
  • 113
  • 196
Dabo
  • 371
  • 1
  • 14

1 Answers1

0

Getting this integration right won't be easy. However, here's what I'm thinking about:

Connecting Python and Tcl

You can run Python inferior to Tcl apparently. According to this wiki page, there's a package called tclpython which can do the basic integration work for you, and the page linked to appears live. The code appears to be here, though it might need some work to make it build. (I've never tried.)

Connecting matplotlib and Tk

You can make matplotlib draw on a Tkinter window, and as long as you can make that Tkinter window with the right options, it will show up. The key is that the underlying system window IDs can be found out from Tk with winfo id $nameOfTheWindow. If you create a frame with the -container option set to true (which turns off some things and turns on a few others; you'll need to set the size explicitly) then that particular frame will be suitable for use with TkAgg on the python/matplotlib side. The key will be to make a toplevel on that side that has the -use option set to the ID retrieved from winfo id. You probably need to make sure that the python side is running its rendering in a separate thread to the outer Tcl/Tk to make the event handling work right (unless you're keen on doing deep event loop hacking; the situation is that you're actually going to have Tcl/Tk inside Python inside Tcl/Tk, as Tkinter works by delegating to a subordinate Tcl/Tk, and getting all this glued together right will be “a bit tricky”).

If that doesn't work, get matplotlib to render as an image (GIF or PNG; the latter is preferred if you've got Tk 8.6) as you can just show that easily via a photo image. This is definitely going to be possible to do without thread games; it's just passing around pure data. Probably slower and not interactive, but that might not matter for what you're doing, and it is easier in the simple case.

You will probably need the second approach if you're on Windows or OSX, as Tk there doesn't actually use X11. (Unless you're using one of the more perverse configuration options, of course.)

Donal Fellows
  • 133,037
  • 18
  • 149
  • 215
  • Thanks for this. My application is critically real-time and multi-threaded (we chose Tcl because of it's it's out-of-the-box event loop and excellent thread model), so I definitely want to avoid hitting disk as with the second option. I'll report back if I have any luck with option 1. – Dabo Jan 18 '16 at 03:17