问题描述
我试图在python中编写一个应用程序来控制使用串行的电机。这一切都在CLI的情况下很好地工作,并且通常是稳定的。但我想知道在这个代码库的基础上添加一个GUI是多么简单吗?
像GTK这样的东西,所以它只在GTK出现时才应用代码?另外,在Python中一般创建GUI:最好是保持GUI特性不变代码并使用类似GTK基于XML的方法(使用gtk.glade.XML()函数)?是否还有其他GUI工具包,它们与Glade / XML /代码爆炸方法类似?感谢您的任何建议。
Andy
首先,将您的应用分成3个独立的模块。
-
实际工作:
foo_cli 模块看起来像这样。
import foo_core
import optparse
def main():
#解析命令-line options
#真正的工作由foo_core完成
如果__name__ ==__main__:
main()
foo_gui 模块可以像这样。
导入foo_core
导入gtk#或任何
def main()
#构建GUI
#实际工作是由foo_core在GUI
$ b的控制下完成的,如果__name__ ==__main__:
main()
这通常就足够了。人们可以信任自己决定他们是否需要CLI或GUI。
如果你想混淆人,你可以写一个 foo.py
try:
import foo_gui $ b $ 脚本可以执行下列操作。 b foo_gui.main()
除ImportError外:
导入foo_cli
foo_cli.main()
I am trying to write an app in python to control a motor using serial. This all works in a CLI situation fine and is generally stable. but I was wondering how simple it was to add a GUI on top of this code base?
I assume there will be more code, but is there a simple way of detecting something like GTK, so it only applied the code when GTK was present?
Also, GUI creation in Python in general: is it best to keep as little GUI specifics out of the code and use something like GTK's XML based approach (using gtk.glade.XML() function)? Are there other GUI toolkits that have a similar approach to the Glade / XML / "Explode in Code" approach?
Thanks for any advice.
Andy
First, break your app into 3 separate modules.
The actual work: foo_core.py.
A CLI module that imports foo_core. Call it foo_cli.py.
A GUI module that imports foo_core. Call it foo_gui.pyw.
The foo_cli module looks like this.
import foo_core import optparse def main(): # parse the command-line options # the real work is done by foo_core if __name__ == "__main__": main()
The foo_gui module can look like this.
import foo_core import gtk # or whatever def main() # build the GUI # real work is done by foo_core under control of the GUI if __name__ == "__main__": main()
That's generally sufficient. People can be trusted to decide for themselves if they want CLI or GUI.
If you want to confuse people, you can write a foo.py script that does something like the following.
try: import foo_gui foo_gui.main() except ImportError: import foo_cli foo_cli.main()
这篇关于我如何在Python APP上创建GUI,以便它可以执行GUI或CLI?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!