如何将 Python Tkinter 代码拆分为多个文件

Ban*_*ora 5 python tkinter python-3.x

这是我在此的头一篇博文!

\n\n

首先这是我的项目的 github 链接(我也是 github 上的菜鸟)。

\n\n

编辑:

\n\n

这是我想要做的一个例子,我有一个大的 Tkinter 类,其中有框架、标签、菜单、按钮以及所有和一些功能。

\n\n

我想让 UI 描述在我的 MakeUI() 中并将我的函数移动到另一个文件,但我仍然需要访问小部件。

\n\n

<主.py>

\n\n
# -*- coding: utf-8 -*-\n\nfrom tkinter import *\nfrom Interface import *\n\n\nFenetre = Tk()\nUI = MakeUI(Fenetre)\n\nUI.mainloop()\n\nUI.destroy()\n
Run Code Online (Sandbox Code Playgroud)\n\n

<接口.py>

\n\n
# -*- coding: utf-8 -*-\n\nfrom tkinter import *\nfrom tkinter.filedialog import *\n\n\nclass MakeUI(Frame):\n\n    def __init__(self, Fenetre, **kwargs):\n\n        # H\xc3\xa9ritage\n        Frame.__init__(self, Fenetre, width=1500, height=700, **kwargs)\n\n        self.pack(fill=BOTH)\n\n        self.FrameInfos = LabelFrame(self, text="Choix des param\xc3\xa8tres", padx=2, pady=2)\n        self.FrameInfos.pack(fill="both", expand="yes", padx=5, pady=5)\n\n        self.MsgInfosCarte = Label(self.FrameInfos, text="Example", width=45)\n        self.MsgInfosCarte.pack(padx=2, pady=2)\n\n    def AfficherCarte(self):\n        self.MsgInfosCarte["text"] = "OK"\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在在这个例子中,我需要将 AfficherCarte 函数移动到另一个文件,如 MapFuncs.py 或其他文件。\n并且我希望 MakeUI 能够调用其他文件 funcs 和其他文件 funcs 来修改界面。

\n\n

我无法正确地做到这一点。

\n\n

感谢您的帮助。

\n

Jos*_*lin 3

为了将修改 GUI 小部件的函数移动到单独的文件中,您可以简单地将小部件实例(或存储该实例的对象)作为函数的输入参数传递:

\n\n

<MapFuncs.py>

\n\n
def AfficherCarte(UI):\n    UI.MsgInfosCarte["text"] = "OK"\n
Run Code Online (Sandbox Code Playgroud)\n\n

<接口.py>

\n\n
import tkinter as tk\nfrom MapFuncs import AfficherCarte\n\nclass MakeUI(tk.Frame):\n\n    def __init__(self, Fenetre, **kwargs):\n\n        # H\xc3\xa9ritage\n        tk.Frame.__init__(self, Fenetre, width=1500, height=700, **kwargs)\n        self.pack()\n\n        self.FrameInfos = tk.LabelFrame(self, text="Choix des param\xc3\xa8tres", padx=2, pady=2)\n        self.FrameInfos.pack(fill="both", expand="yes", padx=5, pady=5)\n\n        self.MsgInfosCarte = tk.Label(self.FrameInfos, text="Example", width=45)\n        self.MsgInfosCarte.pack(padx=2, pady=2)\n\n        # Call function from external file to modify the GUI\n        AfficherCarte(self)\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果您这样做是因为代码变得太大,另一种方法是将 GUI 分为针对界面的每个主要部分的单独的类(请参阅/sf/answers/1222958971/)。

\n