开发者

Python: load a UI from a separate file

开发者 https://www.devze.com 2023-04-12 11:38 出处:网络
G\'day All, I\'m using tkinter for my GUI.Currently when I write an app most of the code is the interface widgets.I know how to import a file of def开发者_JS百科ined functions and use them and I want

G'day All,

I'm using tkinter for my GUI. Currently when I write an app most of the code is the interface widgets. I know how to import a file of def开发者_JS百科ined functions and use them and I want to be able to "import" the UI. That way I can reuse the UI file and declutter the main app.

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.


My recommendation is to not do main=Tk(). Instead, have your UI inherit from 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. For example:

# ui.py
def CreateUI(root)
    ...

# main.py
import ui
def main():
    root = tk.Tk()
    ui.CreateUI(root)


you could pass it as a parameter like 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

0

精彩评论

暂无评论...
验证码 换一张
取 消