在脚本中使用其他.py脚本?

我目前正在做一个tkinter项目,代码变得很长。我想要做的是将其中一些代码分离到.py脚本中,然后将它们导入到主脚本中。我不确定如何让一个单独的脚本像这样工作。我的例子是一个tkinter窗口,它有许多顶层窗口,其中包含大量代码。如果可能的话,我想把它们分开。大概是这样的:

选择 | 换行 | 行号
  1. from Tkinter import *
  2. import OtherScript
  3.  
  4. def NewWindow():
  5.     win = Toplevel()
  6.     Run OtherScript.py
  7.  
  8. root = Tk()
  9. root.geometry('300x300')
  10.  
  11. Button(root, text='Click Me', command=NewWindow).pack(side=BOTTOM)
  12.  
  13. mainloop()
  14.  
  15.  

我不想把其他脚本中的所有代码都放在这里,而是希望导入它,并在单击根窗口按钮后运行它。
在'OtherScript.py'的底部,我添加了:

选择 | 换行 | 行号
  1. if __name__ == "__main__":
  2.     import sys
  3.  
# 回答1


在玩弄了这个之后,我想我已经弄明白了:

选择 | 换行 | 行号
  1. #OtherScript.py
  2.  
  3. from Tkinter import *
  4.  
  5. root = Tk()
  6. root.geometry('300x300')
  7.  
  8. Button(root, text='Exit', command=root.destroy).pack()
  9.  
  10. if __name__ == "__main__":
  11.     mainloop()
  12.  

然后导入具有其他脚本的根窗口:

选择 | 换行 | 行号
  1.  
  2. from Tkinter import *
  3.  
  4. def NewWindow():
  5.     import tknw
  6.  
  7. root = Tk()
  8.  
  9. root.geometry('300x300')
  10.  
  11. Button(root, text='Click Me', command=NewWindow).pack(side=BOTTOM)
  12.  
  13. mainloop()
  14.  

这似乎行得通,但如果不应该这样做,请让我知道。谢谢

# 回答2


我认为所有的导入都应该放在主应用程序文件的顶部。看见
Python代码的样式指南
找一下关于进口的那一节。
# 回答3


Bvdet,这就是我最初尝试的,但我一运行根窗口,导入的窗口就会同时打开。

选择 | 换行 | 行号
  1. from Tkinter import *
  2. import OtherScript
  3.  
  4.  
  5. root = Tk()
  6.  
  7. root.geometry('300x300')
  8.  
  9. Button(root, text='Click Me', command=None).pack(side=BOTTOM)
  10.  
  11. mainloop()
  12.  
  13.  

这样做^将导致根窗口和其他脚本同时运行。

# 回答4


将导入的模块中的代码封装在函数或类中,并在主脚本中调用函数或实例化类。
要导入的脚本的代码示例:

选择 | 换行 | 行号
  1. # module1.py
  2. import Tkinter
  3.  
  4. class LabelWidget(Tkinter.Entry):
  5.     def __init__(self, master, x, y, text):
  6.         self.text = Tkinter.StringVar(master)
  7.  
  8. class EntryWidget(Tkinter.Entry):
  9.     def __init__(self, master, x, y, v):
  10.         Tkinter.Entry.__init__(self, master=master)
  11.  
  12. class EntryGrid(Frame):
  13.     ''' SDS/2 Frame with Tkinter.Entry widgets arranged in columns and rows.'''
  14.     def __init__(self, parent, obj, cols, rows, pattern, anchorPattVar):
  15.         pass
  16.  
  17. class EmbedDialog(object):
  18.  
  19.     def __init__(self, model):
  20.         pass
  21.  
  22. if __name__ == "__main__":
  23.     class Model:
  24.         def __init__(self, **kw):
  25.             for key in kw:
  26.                 setattr(self, key, kw[key])
  27.     x = EmbedDialog(Model(x=12, y=24))

IF语句后面的代码不会在导入模块时执行,而是在文件作为脚本运行时执行。
主剧本:

选择 | 换行 | 行号
  1. import module1
  2. class Model:
  3.     def __init__(self, **kw):
  4.         for key in kw:
  5.             setattr(self, key, kw[key])
  6. dlg = module1.EmbedDialog(Model(x=12, y=24))

标签: python

添加新评论