我目前正在做一个tkinter项目,代码变得很长。我想要做的是将其中一些代码分离到.py脚本中,然后将它们导入到主脚本中。我不确定如何让一个单独的脚本像这样工作。我的例子是一个tkinter窗口,它有许多顶层窗口,其中包含大量代码。如果可能的话,我想把它们分开。大概是这样的:
- from Tkinter import *
- import OtherScript
-
- def NewWindow():
- win = Toplevel()
- Run OtherScript.py
-
- root = Tk()
- root.geometry('300x300')
-
- Button(root, text='Click Me', command=NewWindow).pack(side=BOTTOM)
-
- mainloop()
-
-
我不想把其他脚本中的所有代码都放在这里,而是希望导入它,并在单击根窗口按钮后运行它。
在'OtherScript.py'的底部,我添加了:
- if __name__ == "__main__":
- import sys
-
# 回答1
在玩弄了这个之后,我想我已经弄明白了:
- #OtherScript.py
-
- from Tkinter import *
-
- root = Tk()
- root.geometry('300x300')
-
- Button(root, text='Exit', command=root.destroy).pack()
-
- if __name__ == "__main__":
- mainloop()
-
然后导入具有其他脚本的根窗口:
-
- from Tkinter import *
-
- def NewWindow():
- import tknw
-
- root = Tk()
-
- root.geometry('300x300')
-
- Button(root, text='Click Me', command=NewWindow).pack(side=BOTTOM)
-
- mainloop()
-
这似乎行得通,但如果不应该这样做,请让我知道。谢谢
# 回答2
我认为所有的导入都应该放在主应用程序文件的顶部。看见
Python代码的样式指南
找一下关于进口的那一节。
# 回答3
Bvdet,这就是我最初尝试的,但我一运行根窗口,导入的窗口就会同时打开。
- from Tkinter import *
- import OtherScript
-
-
- root = Tk()
-
- root.geometry('300x300')
-
- Button(root, text='Click Me', command=None).pack(side=BOTTOM)
-
- mainloop()
-
-
这样做^将导致根窗口和其他脚本同时运行。
# 回答4
将导入的模块中的代码封装在函数或类中,并在主脚本中调用函数或实例化类。
要导入的脚本的代码示例:
- # module1.py
- import Tkinter
-
- class LabelWidget(Tkinter.Entry):
- def __init__(self, master, x, y, text):
- self.text = Tkinter.StringVar(master)
-
- class EntryWidget(Tkinter.Entry):
- def __init__(self, master, x, y, v):
- Tkinter.Entry.__init__(self, master=master)
-
- class EntryGrid(Frame):
- ''' SDS/2 Frame with Tkinter.Entry widgets arranged in columns and rows.'''
- def __init__(self, parent, obj, cols, rows, pattern, anchorPattVar):
- pass
-
- class EmbedDialog(object):
-
- def __init__(self, model):
- pass
-
- if __name__ == "__main__":
- class Model:
- def __init__(self, **kw):
- for key in kw:
- setattr(self, key, kw[key])
- x = EmbedDialog(Model(x=12, y=24))
IF语句后面的代码不会在导入模块时执行,而是在文件作为脚本运行时执行。
主剧本:
- import module1
- class Model:
- def __init__(self, **kw):
- for key in kw:
- setattr(self, key, kw[key])
- dlg = module1.EmbedDialog(Model(x=12, y=24))