rectangletangle
rectangletangle

Reputation: 52911

Importation in Python

I have a little module that creates a window (program1). I've imported this into another python program of mine (program2).

How do I make program 2 do the function call self.Main() that's in program1?

Also how do I go about transferring values across programs?

Say in program1 x = 'hello', how do I get the value of x in program2?

This is program1.

import Tkinter

class Class(Tkinter.Tk):

    def __init__(self, parent):

        Tkinter.Tk.__init__(self, parent)
        self.parent = parent

        self.Main()

    def Main(self):
        self.button= Tkinter.Button(self,text='hello')
        self.button.pack()

def run():
    app = Class(None)
    app.mainloop()

if __name__ == "__main__":
    run()

Upvotes: 0

Views: 119

Answers (2)

Cheezey
Cheezey

Reputation: 720

Along with what cecilkorik said, you can do:

from program1 import *

That will let you use 'x' on its own, without doing:

program1.x

However, import * can sometimes overwrite important things and you may just want to do:

from program1 import x

To only import one specific thing.

Upvotes: 0

cecilkorik
cecilkorik

Reputation: 1431

If program1 is saved in program1.py, then in program2 what you do is:

import program1

# this will show program1's "x" variable
print program1.x

# this will set program1's "x" variable
program1.x = "hello again"

# this will run your program1's "run" function, which 
# should create the Tkinter window for you
program1.run()

# if you REALLY want to call "Main" yourself, which will
# probably just break Tkinter since your init function
# already calls Main() once, you can do...
myclass = program1.Class(None)
myclass.Main()

Upvotes: 3

Related Questions