Accessing ShowBase from other classes

from direct.showbase.ShowBase import ShowBase
from direct.gui.DirectGui import *

class Core(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        ButtonBar()


class ButtonBar():
    def __init__(self):
        self.btnsr = DirectButton(parent=pixel2d) # how do I access ShowBase from this class?


core = Core()
core.run()

With the current code I cant parent btnsr to pixel2d as ButtonBar has no access to ShowBase. How do I access ShowBase while keeping the code separated into two classes

What you have there should work, and indeed, on my machine it does.

However, there is one problem: you haven’t set a scale on your button, and as pixel2d uses a scale of 1 Panda-unit per pixel (I think it is), your button at its default size is too small to easily see. If you give it a larger scale (say, “300”), you should see it peek in at the top-left of the window (the origin of pixel2d).

(Unless you’re seeing some error that I’m not getting, of course, in which case: what are you seeing on your end?)

More generally, if I’m not much mistaken, ShowBase establishes a global variable named “base” that, along with several other globally-accessible things (including “render” and “pixel2d”), should be accessible from pretty much anywhere.

You can thus do things like this:

from direct.showbase.ShowBase import ShowBase
from direct.gui.DirectGui import *

class Core(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        self.cat = "Kitty"

class SomeOtherClass():
    def __init__(self):
        print (base.cat)
        print (base.win.getSize())

core = Core()
mew = SomeOtherClass()
core.run()

Which should print “Kitty”, followed by “LVecBase2i(<x>, <y>)”, where <x> and <y> are the width and height of the window–in my case, they’re 800 and 600, repsectively.

(The call to “run” is superfluous to running the print-statements in the example above.)

using base seems to work just fine :smiley: thank you! Quick question since you know panda3d better than me, how do it make it so that the button pos changes automatically when the window size changes? I tried setting pos relative to win.getSize() but that doesnt seem to update. edit: i’d also like the scale to update

It seems that using aspect2d’s a2dTopLeft etc… updates the buttons pos

I’m glad that you seem to have found those NodePaths, and the earlier help is my pleasure. :slight_smile: