在Python中导入

时间:2010-11-21 03:37:37

标签: python tkinter

我有一个创建窗口的小模块(program1)。我把它导入了我的另一个python程序(program2)。

如何使程序2执行函数调用self.Main()在program1中?

另外,我如何跨程序传输值?

在program1 x ='hello'中说,如何在program2中获取x的值?

这是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()

2 个答案:

答案 0 :(得分:3)

如果program1保存在program1.py中,那么在program2中你所做的是:

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()

答案 1 :(得分:0)

与cecilkorik所说的一样,你可以这样做:

from program1 import *

这样可以让你自己使用'x',而不用:

program1.x

但是,import *有时会覆盖重要的事情,您可能只想这样做:

from program1 import x

仅导入一件特定的东西。