next up previous contents index
Next: Controlling VMD from Python Up: Python callbacks Previous: Python callbacks   Contents   Index

Using Tkinter menus in VMD

The object-oriented interface to Tk known as Tkinter is included with the embedded Python interpreter. However, since the event loop for these menus must run within VMD's main event loop, some modification to the Python code will be necessary to use Tkinter menus within VMD. Using the normal mainloop() method will cause VMD to freeze up.

The callback mechanism provides a way for Tkinter menus to be updated each time through VMD's event loop. The following code shows how to override the Tk mainloop() method to let Tkinter menus peacefully coexist with VMD's event loop:

import VMDCallback
import Tkinter

def cb(foo, bar):
        foo.update()

class VMDMenu(Tkinter.Tk):
        def mainloop(self):
                VMDCallback.add_callback('display_update', cb, self)
                self.bind("<Destroy>", self.unregister)

        def unregister(self, event=None):
                VMDCallback.del_callback('display_update', cb, self)

        def __del__(self):
                # unregister from display_update
                try:
                        self.unregister()
                except:
                        pass

VMDMenu instances can be used much like Tk instances. Here is an example, taken from John Grayson's "Python and Tkinter Programming", with the only difference being Tk replaced by VMDMenu:

from Tkinter import *
import VMDMenu

class App:
        def __init__(self, master):
                Button(master, text='Left').pack(side=LEFT)
                Button(master, text='Center').pack(side=LEFT)
                Button(master, text='Right').pack(side=LEFT)

root = VMDMenu.VMDMenu()
root.option_add('*font', ('verdana', 12, 'bold'))
root.title("Pack - Example 1")
display = App(root)
root.mainloop()

Other strategies may also be of use, depending on your application.



vmd@ks.uiuc.edu