首页 > 解决方案 > 如何从另一个 .py 文件调用模块

问题描述

第一次发帖!

我对 python(和编程!)相当陌生,我已经开始制作一个基本的 tkinter 程序。代码现在变得很长,我想在不同的 .py 文件之间拆分它以使其更易于导航。到目前为止,我所有的代码都存在于类中,将主窗口、计算函数、辅助窗口等分开。

第一个问题,这样拆分代码是否被认为是一种好习惯?我觉得是,但想确定!

其次,如何处理文件之间的模块的最佳方式是什么?

例如,我在 main_window.py 文件中导入了 tkinter 和 matplotlib。我有 main_window 类函数,它调用一个不同的类,我想将它移动到另一个文件,但是这个辅助类有一行调用 tkinter。我想通过辅助函数传递 self ,以便它使用相同的实例。

这是一个示例代码来说明。第一个文件 main_window.py:

# main_window.py    

import tkinter as tk
import matplotlib
import matplotlib.pyplot as plt
import app_design  # app_design.py contains the code I want to break out

class MainWindow:
        def __intit__(self, root):
                self.root = root
                self.start_gui()
    
        def start_gui(self):
                # a bunch of code
                ...
                # in reality this is read from a program file on startup                    
                color_mode = "Dark"

                # This is just an example, the matplotlib call in the other app is in the __init__                    
                self.bg_col_mode = tk.StringVar()

                self.bg_col_mode.set(app_design.AppColors(color_mode).background())

                # a bucnh more code of various tk widgets and matplotlib charts
                ...


if __name__ == '__main__':
        app = MainWindow(tk.Tk())
        app.root.mainloop()

然后是我想拆分的一些代码示例。这不是该类引用 MainWindow 类之外的模块的唯一实例,但它作为示例工作:

# app_design.py

class AppColors:
        def __init__(self, color_mode):
                self.color_mode = color_mode

                if self.col_mode == "Dark":
                        self.plt.style.use("Dark")  # it is this .plt call that has moved from the main_window.py file to the new file
                else:
                        self.plt.style.use("Light")

        def background_mode(self):
                if self.color_mode == "Dark":
                        return "#292929"  # colour code
                else:
                        return "#F8F1F1"

希望这是有道理的!

标签: pythonclassmatplotlibtkinterstructure

解决方案


第一个问题,这样拆分代码是否被认为是一种好习惯?我觉得是,但想确定!

我其实不了解自己,我只有后端的代码。

其次,如何处理文件之间的模块的最佳方式是什么?

您只需导入文件(或直接导入函数)。

例子:

文件1.py

def hello(name):
    print("Hello ", name)

文件2.py

from file1 import hello

hello("arjix")

这样就可以直接使用函数hello

或者

import .file1

file1.hello("arjix")

PS:确保这两个文件在同一个文件夹中。


推荐阅读