[英]Python: load a UI from a separate file
G'day All, G'day All,
I'm using tkinter for my GUI. 我将tkinter用于我的GUI。 Currently when I write an app most of the code is the interface widgets. 当前,当我编写一个应用程序时,大多数代码是界面小部件。 I know how to import a file of defined functions and use them and I want to be able to "import" the UI. 我知道如何导入已定义函数的文件并使用它们,并且我希望能够“导入” UI。 That way I can reuse the UI file and declutter the main app. 这样,我可以重用UI文件并整理主应用程序。
The conceptual hurdle I'm facing is that if I declare a window: 我面临的概念障碍是,如果我声明一个窗口:
main = Tk()
how do I then populate "main" from another module? 然后如何从另一个模块填充“主”?
Thanks, A. 谢谢。
you could pass it as a parameter like import my_gui; my_gui.create(main)
您可以将其作为参数import my_gui; my_gui.create(main)
例如import my_gui; my_gui.create(main)
import my_gui; my_gui.create(main)
; import my_gui; my_gui.create(main)
; but for most situations I would recommend working the other way round -- have the GUI file be the file that you execute, and it imports the number-crunching functions from your core-functionality library 但对于大多数情况,我建议您采用另一种方法进行工作-将GUI文件作为您执行的文件,然后从核心功能库中导入数字运算功能
My recommendation is to not do main=Tk()
. 我的建议是不要做main=Tk()
。 Instead, have your UI inherit from Tk. 相反,让您的UI继承自Tk。 For example: 例如:
# in ui.py
import Tkinter as tk
class MyApp(tk.Tk):
def __init__(self, *args, **kwargs):
...
# in main.py
import ui
def main():
main = ui.MyApp()
main.mainloop()
If you don't like inheriting from tk.Tk
, your other option is to create your main window and then pass it as an argument to whatever code you have that creates the GUI. 如果您不喜欢从tk.Tk
继承,则另一个选择是创建主窗口,然后将其作为参数传递给创建GUI的任何代码。 For example: 例如:
# ui.py
def CreateUI(root)
...
# main.py
import ui
def main():
root = tk.Tk()
ui.CreateUI(root)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.