Python - access variable in another class

6,202

Just pass around your mainwindow instance, something like this:

class MyWindow(Gtk.Window):
    def __init__(self):
        # Do your thing...

        self.spam = "spam'n'eggs"

    def on_opendialog_clicked(self, widget):
        dialog = MyDialog(self)
        dialog.run()
        dialog.destroy()

class MyDialog(Gtk.Dialog):
    def __init__(self, mainwindow):
        # ...

        print(mainwindow.spam)

Have a look at my answer in this question too which is almost similar, only the other way around.

Share:
6,202

Related videos on Youtube

user26030
Author by

user26030

Updated on September 18, 2022

Comments

  • user26030
    user26030 over 1 year

    I have 1 main window and 1 dialog. Now I need to access variable in main window from dialog.

    For example in java we have 2 classes: demo and myclass In my class I have following code: public static int number=5; Then I simply access it using myclass.number.

    How to do it in python using quickly ide?

    Do I need to import main window in dialog to get access to static variable?

    • onse
      onse almost 12 years
      I have no idea what quickly is but first of all you wouldn't normally declare a variable public in Java but private (or protected). Second I think that in python you would do import myclass in your other class, then you would instantiate it m=myclass() and should be able to access it m.number. You can also acccess it without instantiation. See stackoverflow.com/questions/68645/… for further information.
    • user26030
      user26030 almost 12 years
      To make example more simple I put public :D
  • user26030
    user26030 almost 12 years
    Error is on line: dialog = MyDialog(self)
  • user26030
    user26030 almost 12 years
    Here you can see the code generated by quickly which probably causes error: pastebin.com/68fNcMdD
  • Timo
    Timo almost 12 years
    Please provide an actual traceback. "Probably" and "error" aren't of any help.
  • user26030
    user26030 almost 12 years
    TypeError: Must be string, not SampleWindow Here you can find sample application: ubuntuone.com/5eCaimCkGxOJn1SxUTTh5T
  • user26030
    user26030 almost 12 years
    Here is my code:ubuntuone.com/5eCaimCkGxOJn1SxUTTh5T I dont have init