Problem with escape key and sys.exit

Hi, I’m just learning Panda3D and have messed about with some of the examples, mostly with no problems, but I’m getting strange behaviour from the escape key keyboard event.

I’ve adpated the example code from the Keyboard_Support section of the manual to just print the letter ‘a’ when ‘a’ is pressed, that worked fine. When I added the line, self.accept(‘escape’, sys.exit()), to exit the game when escape is pressed into my test class, the game window dissapeared immediately on load. If I put the sys.exit event handler outside the class and call it from base, it works fine. Any idea what I’m doing wrong? Here’s my code.

import direct.directbase.DirectStart
from direct.showbase.DirectObject import DirectObject
import sys

# This works fine
#base.accept('escape', sys.exit)

class ReadKeys(DirectObject):
  def __init__(self):

    # This works fine too
    self.accept('a', self.printa)

    # This causes the Panda window to dissapear immediately
    #self.accept('escape', sys.exit())

    # So does this
    #base.accept('escape', sys.exit())

  def printa(self):
        print "a"

keys = ReadKeys()
run()

Thanks for any help.

Mark

Hm, this is wrong:

self.accept('escape', sys.exit())

At the point that code is executed, sys.exit() is called and the result of that function call is passed to self.accept. You should be passing the function itself, like this:

self.accept('escape', sys.exit)

That happens to be the difference between the function call you put outside the class definition and the one you put inside it. :slight_smile:

Alternatively, you can wrap it in a lambda:

self.accept('escape', lambda: sys.exit())

Thank you very much, that was precisely the problem. Looks like my Python skills need some work :blush: