Tk is great, but sometimes it just isn’t fast enough. SDL is fast, but has no support for input dialogs and other GUI conventions. By embedding an SDL surface in a Tk window you get the best of both worlds. Whether you want to use Tk to add a nice GUI to an SDL app or want to access SDL via Tcl/Tk, this article will show you how.
Embedding the SDL Surface
To embed an SDL surface in another window you have to alter the
SDL_WINDOWID environmental variable so that it matches the ID of the window that you want the SDL surface embedded in. This must be done after the main window is displayed and before SDL_Init() is called.
To ensure that the Tk window is displayed you need to call something like:
From Tcl you must provide a window for the SDL surface to be embedded in. This should have the
background set to
"" otherwise you will get problems when other windows cover it:
Then to get the window ID and set
The above uses
SDL_putenv() rather than
putenv() as this is recommended by an old SDL GUI FAQ
From this point you can call
SDL_SetVideoMode(), but do remember to use the
The Event Loop
You must have an event loop that calls both SDL_PollEvent() and Tk_DoOneEvent(). The events will be handled mostly by Tk. However, you do need to detect SDL_QUIT from SDL_PollEvent() because SDL converts SIGTERM to this.
Handling Key Release Events
From Tcl you can handle whichever events you need to detect. For example to bind the
<KeyRelease> event to a key handler:
Handling Expose Events
SDL also needs to know when the screen should be redrawn. From Tcl:
And to provide the
A Small Demonstration
I have created the sdl_and_tk_demo on github to demonstrate how to put this altogether. The README contains information on how to compile and run the demo. This demo was inspired by Kent Mein’s SDL and Tk MDI demo.