利用python 连接cad对勘测定界图斑提取与导入

import win32com.client
import pythoncom
import math
import tkinter as tk
from tkinter import filedialog, messagebox
from decimal import Decimal
import datetime
from pyautocad import Autocad, APoint
import numpy
import socket
from sys import exit

'''打开选择文件夹对话框'''

now_time = datetime.datetime.now().strftime('%Y-%m-%d')
window0 = tk.Tk()
window0.title("勘测定界图斑提取与导入2.0")
window0.geometry('320x510+1500+200')  # 290 160为窗口大小,+1000 +10 定义窗口弹出时的默认展示位置
window0['background'] = 'LightPink'
window0.resizable(0, 0)
pc_name = socket.gethostname()


# if pc_name not in "scc.ttcn.cn":
#     tk.messagebox.showinfo('警告', "创作不易,支持正版\n\n个人购买程序只需:200人民币\n请与[email protected]联系\n")
#     exit()
def help_text():
    tk.messagebox.showinfo('抱歉', "请联系放放风。")
    # system("start ./help\help.docx")


def about():
    tk.messagebox.showinfo('关于', "勘测定界图斑提取与导入2.0\n状态:已激活\n\nby:放放风 2021.02.10 \n更多功能请联系:[email protected]")


menubar = tk.Menu(window0)

file_menu = tk.Menu(menubar, tearoff=False)
file_menu.add_command(label='帮助文档', command=help_text)

menubar.add_cascade(label='菜单', menu=file_menu)
menubar.add_command(label='关于', command=about)

window0.config(menu=menubar)


def cal_ang(point_1, point_2, point_3):
    """
    根据三点坐标计算夹角
    :param point_1: 点1坐标
    :param point_2: 点2坐标
    :param point_3: 点3坐标
    :return: 返回任意角的夹角值,这里只是返回点2的夹角
    """
    a = math.sqrt(
        (point_2[0] - point_3[0]) * (point_2[0] - point_3[0]) + (point_2[1] - point_3[1]) * (point_2[1] - point_3[1]))
    b = math.sqrt(
        (point_1[0] - point_3[0]) * (point_1[0] - point_3[0]) + (point_1[1] - point_3[1]) * (point_1[1] - point_3[1]))
    c = math.sqrt(
        (point_1[0] - point_2[0]) * (point_1[0] - point_2[0]) + (point_1[1] - point_2[1]) * (point_1[1] - point_2[1]))
    A = math.degrees(math.acos((a * a - b * b - c * c) / (-2 * b * c)))
    # B = math.degrees(math.acos((b * b - a * a - c * c) / (-2 * a * c)))
    # C = math.degrees(math.acos((c * c - a * a - b * b) / (-2 * a * b)))
    return A


def listz(a):
    n = 0
    b = []
    ll = (len(a)) / 2
    for x in range(int(ll)):
        m = a[n]
        s = a[n + 1]
        v = [m, s]
        b.append(v)
        n += 2
    return b


def iangle(pointA, listB):
    t = 0
    angle = 0
    for _ in listB:
        if t < len(listB) - 1:
            s = cal_ang(pointA, listB[t], listB[t + 1])
            t += 1
            angle += s
        elif t == len(listB) - 1:
            s = cal_ang(pointA, listB[t], listB[0])
            angle += s
    return angle


def Polygon_area(plan):  # 计算面积
    s = 0
    plan2 = [[Decimal(x), Decimal(y)] for x, y in plan]

    point_num = len(plan2)
    for i in range(point_num):
        s += (plan2[i][1] * (plan2[i - 1][0] - plan2[(i + 1) % point_num][0]))
    mj = abs((s / Decimal(2)) / 10000)
    mj = round(mj, 4)
    return mj  # 返回面积(米);坐标,列表内值为字符串


def vtpnt(x, y, z=0):
    """坐标点转化为浮点数"""
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y, z))


def vtobj(obj):
    """转化为对象数组"""
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_DISPATCH, obj)


def vtFloat(list):
    """列表转化为浮点数"""
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, list)


def vtInt(list):
    """列表转化为整数"""
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_I2, list)


def vtVariant(list):
    """列表转化为变体"""
    return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_VARIANT, list)


class Extract:
    acad = win32com.client.Dispatch("AutoCAD.Application")
    doc = acad.ActiveDocument
    doc.Utility.Prompt("\n醉后不知天在水\n满船清梦压星河\n")
    mp = doc.ModelSpace

    def __init__(self):
        self.text_c = dict()
        self.File_path = ""
        self.Save_path = ""
        self.area = None

    def open(self):  # 打开
        File_path = filedialog.askopenfilenames(filetypes=[("文本", "txt")], title="选择需要转换的文本")  # 获取需要转换的规划文件绝对路径
        self.File_path = File_path

    def save(self):  # 保存
        Save_path = filedialog.askdirectory()
        self.Save_path = Save_path

    def Select_element(self):
        tk.messagebox.showinfo('提示', "请在屏幕拾取图元,以Enter键结束")
        try:
            Extract.doc.SelectionSets.Item("SS1").Delete()
        except:
            # print("Delete selection failed")
            tk.messagebox.showinfo('警告', "Delete selection failed")
        slt = Extract.doc.SelectionSets.Add("SS1")
        slt.SelectOnScreen()
        # print("请在屏幕拾取图元,以Enter键结束")

        text_coordinates = {
     }  # 文本坐标
        pl_coordinates = []  # 线段坐标
        poly_area1 = []
        poly_area2 = []
        for x in slt:
            if x.ObjectName == "AcDbText":
                text_coordinat = {
     x.InsertionPoint: x.TextString}  # 文本坐标:文本
                text_coordinates.update(text_coordinat)  # 添加到字典

            if x.ObjectName == "AcDbPolyline":
                pl_coordinates.append(x.Coordinates)
        if len(text_coordinates) == len(pl_coordinates):
            for text_point in text_coordinates.keys():
                A = list(text_point[:-1])
                for coodinate in pl_coordinates:
                    B = list(coodinate)
                    C = listz(B)
                    angle = iangle(A, C)
                    if 359.99 < angle < 360.01:
                        text_name = text_coordinates[text_point]
                        text_val = [[x, y] for x, y in C]  # x,y格式

                        if "扣除" in text_name:
                            poly_area1.append([text_name, text_val])
                        else:
                            poly_area2.append([text_name, text_val])
                            self.text_c.update({
     text_name: text_val})

        for pf in poly_area2:
            for af in poly_area1:
                if pf[1] == af[1]:
                    l = poly_area1.index(af)
                    poly_area1.pop(l)
        for kf in poly_area1:
            self.text_c.update({
     kf[0]: kf[1]})


myobj = Extract()

'''
规划
'''


def plane():
    myobj.save()  # 选择保存位置
    daihao = int(textA2_var.get())
    houzhui = textA3_var.get()
    weishu = int(textA4_var.get())

    if not myobj.Save_path:
        tk.messagebox.showinfo('警告', "请选择保存位置!")
        return
    for path_name in myobj.text_c.keys():
        path = myobj.Save_path + "/" + path_name + houzhui + ".txt"
        plane_text = open(path, "w")

        vla = myobj.text_c[path_name]
        count = 1
        for t in vla:
            if count < len(vla):
                t = str(count) + ",1,1," + "J" + str(count) + "," + str(round(t[1], weishu)) + "," + str(
                    round(daihao + t[0], weishu))
                plane_text.writelines(t)
                plane_text.write("\n")
                count += 1
            elif count == len(vla):
                t = str(count) + ",1,1," + "J" + str(count) + "," + str(round(t[1], weishu)) + "," + str(
                    round(daihao + t[0], weishu))
                plane_text.writelines(t)
                plane_text.write("\n")
                t = str(count + 1) + ",1,1," + "J1" + "," + str(round(vla[0][1], weishu)) + "," + str(
                    round(daihao + vla[0][0], weishu))
                plane_text.writelines(t)
        plane_text.close()
    tk.messagebox.showinfo('提示', "成功,请检查数据")


def plan_merge():
    """打开选择文件夹对话框"""
    windows2 = tk.Toplevel()
    windows2.title("规划坐标合并1.0  cby: 放放风")
    windows2.geometry('790x465+500+200')  # 290 160为窗口大小,+1000 +10 定义窗口弹出时的默认展示位置
    windows2['background'] = 'Pink'
    windows2.resizable(0, 0)
    v = tk.StringVar()
    listbox = tk.Listbox(windows2, height=20, width=90, listvariable=v)

    #
    # 处理单击选项
    def show(event):
        # nearest可以传回最接近y坐标在Listbox的索引
        # 传回目前选项的索引
        listbox.index = listbox.nearest(event.y)

    # 处理拖拽选项
    def showInfo(event):
        # 获取目前选项的新索引
        newIndex = listbox.nearest(event.y)
        # 判断,如果向上拖拽
        if newIndex < listbox.index:
            # 获取新位置的内容
            x = listbox.get(newIndex)
            # 删除新内容
            listbox.delete(newIndex)
            # 将新内容插入,相当于插入我们移动后的位置
            listbox.insert(newIndex + 1, x)
            # 把需要移动的索引值变成我们所希望的索引,达到了移动的目的
            listbox.index = newIndex
        elif newIndex > listbox.index:
            # 获取新位置的内容
            x = listbox.get(newIndex)
            # 删除新内容
            listbox.delete(newIndex)
            # 将新内容插入,相当于插入我们移动后的位置
            listbox.insert(newIndex - 1, x)
            # 把需要移动的索引值变成我们所希望的索引,达到了移动的目的
            listbox.index = newIndex

    def listbox_delete():
        listbox.delete(0, tk.END)

    #

    # 查找列表中指定分隔符所有位置,返回列表-------------------------------------------
    def text_pos(stra, delimiter):
        ly = [-1]
        for x in range(stra.count(delimiter)):
            ly.append(stra.index(delimiter, ly[-1] + 1))
        return ly[1:]

    # 清除文本中的空格和回车--------------------------------------------------------
    def filter_txt(patchw):
        new_listw = []
        charw = ""
        with open(patchw) as f:
            contentsw = f.readlines()
            for linew in contentsw:
                for xw in linew:
                    if xw != " ":
                        charw += xw
                new_listw.append(charw)
                charw = ""
        filter_listw = [w for w in [r.replace("\n", "") for r in new_listw] if w != '']
        return filter_listw

    # 返回保存文件名 ------------------------------------------------------------
    def fileSave():
        filenewpath = filedialog.asksaveasfilename(defaultextension='.txt', filetypes=[("TXT", ".txt")],
                                                   title="请选择要保存的位置")  # 设置保存文件,并返回文件名
        return filenewpath

    # 不加40-----------------------------------------------------------------------

    def txt_merge():
        Folderpath = filedialog.askopenfilenames(filetypes=[("文本", "txt")], title="请选择需要合并的规划文件")

        if not Folderpath:
            tk.messagebox.showinfo('警告', "请选择需要合并的规划坐标")
        return Folderpath

    #
    def list_save():  # 选择需要处理的文件,循环插入路径到列表框
        for x in txt_merge():
            listbox.insert(tk.END, x)
            listbox.bind('', show)
            listbox.bind('', showInfo)

    def txt_merge3():
        plan = open(fileSave(), 'w')  # 打开保存文件的文件
        plan_list = open("list.txt", 'w')  # 打开list.txt,没有创建
        lxo = v.get().split("'")
        xxo = [xxj for xxj in lxo if len(xxj) > 3]
        n0, n1 = 0, 0
        n2 = 0
        for filepath in xxo:  # 循环选择的文件路径
            n1 += 1
            if "扣除" in filepath:
                n1 -= 1
                n2 += 1

                for line in filter_txt(filepath):  # filter_txt清除文件中的空格和回车,返回列表。循环列表
                    n0 += 1
                    str_modify_list1 = line.split(",")
                    str_modify_list1[0] = str(n0)
                    str_modify_list1[1] = str(n1)
                    str_modify_list1[2] = str(n2)
                    str_modify_list_hebing1 = ",".join(str_modify_list1)
                    plan.writelines(str_modify_list_hebing1)
                    plan.write('\n')
            else:
                for line in filter_txt(filepath):  # filter_txt清除文件中的空格和回车,返回列表。循环列表
                    n0 += 1
                    str_modify_list1 = line.split(",")
                    str_modify_list1[0] = str(n0)
                    str_modify_list1[1] = str(n1)
                    str_modify_list_hebing1 = ",".join(str_modify_list1)
                    plan.writelines(str_modify_list_hebing1)
                    plan.write('\n')
                    n2 = 1
            plan_list.write(filepath + "\n")
        plan.close()
        plan_list.close()
        tk.messagebox.showinfo('提示', "合并成功\n\n合并顺序保存在:list.txt")
        return n1

    listbox.grid(row=0, column=0, rowspan=4, columnspan=5)
    tk.Button(windows2, width=20, height=5, text="选择", command=list_save, bg="Yellow").grid(row=0, column=6)
    tk.Button(windows2, width=20, height=5, text="合并", command=txt_merge3, bg="Lawngreen").grid(row=2, column=6)

    tk.Button(windows2, width=20, height=5, text="清空", command=listbox_delete, bg="Deepskyblue").grid(row=3, column=6)

    windows2.mainloop()


'''
二调
'''


def two_coordinate():
    myobj.save()
    daihao = int(textA2_var.get())
    houzhui = textA3_var.get()
    weishu = int(textA4_var.get())
    if not myobj.Save_path:
        tk.messagebox.showinfo('警告', "请选择保存位置!")
        return
    for path_name in myobj.text_c.keys():
        path = myobj.Save_path + "/" + path_name + houzhui + ".txt"
        two_text = open(path, "w")
        vla = myobj.text_c[path_name]
        count = 1
        for t in vla:
            if count < len(vla):
                t = str(round(daihao + t[0], weishu)) + "," + str(round(t[1], weishu))
                two_text.writelines(t)
                two_text.write("\n")
                count += 1
            elif count == len(vla):
                t = str(round(daihao + t[0], weishu)) + "," + str(round(t[1], weishu))
                two_text.writelines(t)
                two_text.write("\n")
                t = str(round(daihao + vla[0][0], weishu)) + "," + str(round(vla[0][1], weishu))
                two_text.writelines(t)
        two_text.close()
    tk.messagebox.showinfo('提示', "成功,请检查数据!")


'''
供地
'''
'''打开选择文件夹对话框'''


def Gd():
    window = tk.Toplevel()
    window.title("供地坐标提取与合并2.0  by: 放放风")
    window.geometry('900x555+500+200')  # 290 160为窗口大小,+1000 +10 定义窗口弹出时的默认展示位置
    window['background'] = 'LightPink'
    window.resizable(0, 0)
    v = tk.StringVar()
    listbox = tk.Listbox(window, height=20, width=90, listvariable=v)
    daihao = int(textA2_var.get())

    # 处理单击选项
    def show(event):
        # nearest可以传回最接近y坐标在Listbox的索引
        # 传回目前选项的索引
        listbox.index = listbox.nearest(event.y)

    # 处理拖拽选项
    def showInfo(event):
        # 获取目前选项的新索引
        newIndex = listbox.nearest(event.y)
        # 判断,如果向上拖拽
        if newIndex < listbox.index:
            # 获取新位置的内容
            x = listbox.get(newIndex)
            # 删除新内容
            listbox.delete(newIndex)
            # 将新内容插入,相当于插入我们移动后的位置
            listbox.insert(newIndex + 1, x)
            # 把需要移动的索引值变成我们所希望的索引,达到了移动的目的
            listbox.index = newIndex
        elif newIndex > listbox.index:
            # 获取新位置的内容
            x = listbox.get(newIndex)
            # 删除新内容
            listbox.delete(newIndex)
            # 将新内容插入,相当于插入我们移动后的位置
            listbox.insert(newIndex - 1, x)
            # 把需要移动的索引值变成我们所希望的索引,达到了移动的目的
            listbox.index = newIndex

    #
    def listbox_delete():
        listbox.delete(0, tk.END)

    #
    def open_hebing():
        Filer_paths = filedialog.askopenfilenames(filetypes=[("文本", "txt")], title="供地坐标合并")  # 获取需要转换的规划文件绝对路径
        if not Filer_paths:
            tk.messagebox.showinfo('警告', "请选择需要合并的的供地坐标!")
            return
        return Filer_paths

    def list_save2():  # 选择需要处理的文件,循环插入路径到列表框
        for x in open_hebing():
            listbox.insert(tk.END, x)
            listbox.bind('', show)
            listbox.bind('', showInfo)

    def get_hebing():
        n = 0
        textk = []
        save_text = filedialog.asksaveasfilename(defaultextension='.txt', filetypes=[("TXT", ".txt")],
                                                 title="请输入保存的文件名")
        if not save_text:
            tk.messagebox.showinfo('警告', "请输入保存的文件名!")
            return
        plan = open(save_text, "w")
        plan2 = open("list1.txt", "w")
        lxo = v.get().split("'")
        xxo = [xxj for xxj in lxo if len(xxj) > 3]  # 获取的列表框值提取
        for x in xxo:
            plan2.write(x)
            plan2.write("\n")
            n += 1
            with open(x) as f:
                contentsw = f.readlines()
                if n == 1:
                    textk.append(contentsw)
                else:
                    if "扣除地块" in x:
                        n -= 2  # 地块号为1时,在列表中的位置为0
                        if n == 0:  #
                            textk[n].append("\n")
                            for c in contentsw[13:]:
                                textk[n].append(c)  # 添加扣除地块,扣除地块不需要前面属性值,contentsw取第13个位置
                            k0 = textk[n][12].split(",")  # 第一个列表第12个值切片

                            k2 = k0[0]  # 取到列表12的位置第1个值,原地块的jzd个数
                            k22 = k0[1]  # 取到列表12的位置第2个值,原地块的面积
                            k1 = (contentsw[12].split(","))[0]  # 取到循环contentsw的第十二个位置切片的第1个位置--扣除地块的jzd个数
                            k11 = (contentsw[12].split(","))[1]  # 取到循环contentsw的第十二个位置切片的第2个位置--扣除地块的面积
                            k3 = int(k2) + int(k1)  # jzd个数相减
                            k33 = Decimal(k22) - Decimal(k11)  # 地块面积相减
                            k0[0] = str(k3)  # 列表k0的第一个值替换为相减的jzd
                            k0[1] = str(k33)  # 列表k0的第二个值替换为相减的面积
                            textk[n][12] = (",".join(k0))  # 列表第n(0)的第12个位置替换为k0--替换的的相减jzd个数,相减的面积
                            n += 1  # 因为0+1还是0所以+1让列表继续循环
                        elif n > 0:  # 地块号为2时,在列表中的位置为1
                            textk[n].append("\n")
                            for c in contentsw[13:]:
                                textk[n].append(c)  # 添加扣除地块,扣除地块不需要前面属性值,contentsw取第13个位置
                            k0 = textk[n][0].split(",")  # 地块2在列表中位置为1,取位置1的第12个值切片
                            k2 = k0[0]  # 取到列表12的位置第1个值,原地块的jzd个数
                            k22 = k0[1]  # 取到列表12的位置第2个值,原地块的面积
                            k1 = (contentsw[12].split(","))[0]  # 取到循环contentsw的第十二个位置切片的第1个位置--扣除地块的jzd个数

                            k11 = (contentsw[12].split(","))[1]  # 取到循环contentsw的第十二个位置切片的第2个位置--扣除地块的面积

                            k3 = int(k2) + int(k1)  # jzd个数相减
                            k33 = Decimal(k22) - Decimal(k11)  # 地块面积相减
                            k0[0] = str(k3)  # 列表k0的第一个值替换为相减的jzd
                            k0[1] = str(k33)  # 列表k0的第二个值替换为相减的面积
                            textk[n][0] = (",".join(k0))  # 列表第n(0)的第12个位置替换为k0--替换的的相减jzd个数,相减的面积
                            n += 1

                    else:
                        textk.append(contentsw[12:])

        for xa in textk:
            plan.writelines(xa)
            plan.write("\n")
        plan2.close()
        plan.close()
        tk.messagebox.showinfo("提示!", "合并成功!")
        return

    # ------------------------------------------------------
    def Polygon_area(plan):  # 计算面积
        s = 0
        plan2 = [[Decimal(x), Decimal(y)] for x, y in plan]

        point_num = len(plan2)
        for i in range(point_num):
            s += (plan2[i][1] * (plan2[i - 1][0] - plan2[(i + 1) % point_num][0]))
        mj = abs((s / Decimal(2)) / 10000)
        mj = round(mj, 4)
        return mj  # 返回面积(米);坐标,列表内值为字符串

    # -----------------------------------------------------
    def Land_supply_coordinates(points):
        n = 0
        mm = []
        # t1 = text1_var.get()
        t2 = text2_var.get()
        t3 = text3_var.get()
        t4 = text4_var.get()
        t5 = text5_var.get()
        t6 = text6_var.get()
        t7 = text7_var.get()
        t8 = text8_var.get()
        t9 = text9_var.get()
        t10 = text10_var.get()
        t11 = text11_var.get()
        # t12 = text12_var.get()
        t13 = text13_var.get()
        t14 = str(Polygon_area(points))
        t15 = text15_var.get()
        t16 = text16_var.get()
        t17 = text17_var.get()
        t18 = text18_var.get()
        t19 = text19_var.get()
        Text_default_format = [["[属性描述]\n"],
                               ["格式版本号=" + str(t2) + "\n"],
                               ["数据生产单位 = " + str(t3) + "\n"],
                               ["数据生产日期 = " + str(t4) + "\n"],
                               ["坐标系=" + str(t5) + "\n"],
                               ["几度分带 = " + str(t6) + "\n"],
                               ["投影类型 = " + str(t7) + "\n"],
                               ["计量单位 = " + str(t8) + "\n"],
                               ["带号 = " + str(t9) + "\n"],
                               ["精度 = " + str(t10) + "\n"],
                               ["转换参数=" + str(t11) + "\n"],
                               ["[地块坐标]\n"],
                               [t13, t14, t15, t16, t17, t18, t19, "", "@" + "\n"]]  # 地块编号;地块面积;时间;项目名称;类型;图幅号;用地性质
        accuracy = len(t10) - 2
        for x in points:
            n += 1
            if n < len(points):
                mm.append(["J" + str(n), "1", str(round(x[1], accuracy)),
                           str(round(daihao + x[0], accuracy)) + "\n"])  # 加40在这里修改
            elif n == len(points):
                mm.append(["J" + str(n), "1", str(round(x[1], accuracy)), str(round(daihao + x[0], accuracy)) + "\n"])
                mm.append(["J" + str(1), "1", mm[0][2], mm[0][3].replace("\n", "")])
        Text_default_format[12][0] = str(n + 1)
        text_var = Text_default_format + mm
        return text_var

    # ---------------------------------------------------

    def list_save():  # 打开文本文件改为cad中文地块名称
        for x in myobj.text_c.keys():
            listbox.insert(tk.END, x)
            listbox.bind('', show)
            listbox.bind('', showInfo)

    def get_save():  # 选择需要保存的路径,循环列表框返回的路径

        n = 0
        mc = 1
        Save_path = filedialog.askdirectory()  # 返回需要保存的绝对路径

        if not Save_path:
            tk.messagebox.showinfo('警告', "请选择需要保存的路径!")
            return
        else:
            f = v.get().split("'")[1:-1]
            k = [x for x in f if x != ", "]

            for file_name in k:  # 循环key
                n += 1
                Filer_name = file_name  # 获取规划文件文件名
                new_filer = open(Save_path + "/" + Filer_name + "(供地坐标).txt", "w")  # 打开文本,没有创建
                points = myobj.text_c[file_name]
                gh = Land_supply_coordinates(points)

                if "扣除地块" in Filer_name:
                    mc += 1
                    n -= 1
                    gh[12][2] = str(n)  # 扣除地块与地块号保持一致
                    for gg in range(len(gh[13:])):  # 循环列表位置13开始的值
                        gh[13:][gg][1] = str(mc)  # 第二个位置的1改为mc
                else:
                    gh[12][2] = str(n)
                    mc = 1
                for new_lines in gh:  # 循环列表
                    new_filer.writelines(",".join(new_lines))  # 列表用“,”合并,写入
                new_filer.close()  # 关闭文本
            tk.messagebox.showinfo('提示', "成功,请检查数据")
        return

    list_save()
    # 文本框1-------------------------
    lable1 = tk.Label(window, text="[属性描述]", width=15).grid(row=0, column=0)
    text1_var = tk.StringVar()  # 获取text_1输入的值
    text1_var.set(r'默认')
    text1 = tk.Entry(window, textvariable=text1_var, bd=5).grid(row=0, column=1)
    #
    lable2 = tk.Label(window, text="格式版本号", width=15).grid(row=1, column=0)
    text2_var = tk.StringVar()  # 获取text_1输入的值
    text2_var.set(r'1.01版本')
    text2 = tk.Entry(window, textvariable=text2_var, bd=5).grid(row=1, column=1)
    #
    lable3 = tk.Label(window, text="数据生产单位", width=15).grid(row=2, column=0)
    text3_var = tk.StringVar()  # 获取text_1输入的值
    text3_var.set(r'杭州通泰测绘有限公司')
    text3 = tk.Entry(window, textvariable=text3_var, bd=5).grid(row=2, column=1)
    #
    lable4 = tk.Label(window, text="数据生产日期", width=15).grid(row=3, column=0)
    text4_var = tk.StringVar()  # 获取text_1输入的值
    text4_var.set(now_time)
    text4 = tk.Entry(window, textvariable=text4_var, bd=5).grid(row=3, column=1)
    #
    lable5 = tk.Label(window, text="坐标系", width=15).grid(row=4, column=0)
    text5_var = tk.StringVar()  # 获取text_1输入的值
    text5_var.set(r'2000国家大地坐标系')
    text5 = tk.Entry(window, textvariable=text5_var, bd=5).grid(row=4, column=1)
    #
    lable6 = tk.Label(window, text="几度分带", width=15).grid(row=5, column=0)
    text6_var = tk.StringVar()  # 获取text_1输入的值
    text6_var.set(r'3')
    text6 = tk.Entry(window, textvariable=text6_var, bd=5).grid(row=5, column=1)
    #
    lable7 = tk.Label(window, text="投影类型", width=15).grid(row=6, column=0)
    text7_var = tk.StringVar()  # 获取text_1输入的值
    text7_var.set(r'高斯克吕格')
    text7 = tk.Entry(window, textvariable=text7_var, bd=5).grid(row=6, column=1)
    #
    lable8 = tk.Label(window, text="计量单位", width=15).grid(row=7, column=0)
    text8_var = tk.StringVar()  # 获取text_1输入的值
    text8_var.set(r'米')
    text8 = tk.Entry(window, textvariable=text8_var, bd=5).grid(row=7, column=1)

    #
    lable9 = tk.Label(window, text="带号", width=15).grid(row=8, column=0)
    text9_var = tk.StringVar()  # 获取text_1输入的值
    text9_var.set(r'40')
    text9 = tk.Entry(window, textvariable=text9_var, bd=5).grid(row=8, column=1)

    #
    lable10 = tk.Label(window, text="精度", width=15).grid(row=9, column=0)
    text10_var = tk.StringVar()  # 获取text_1输入的值
    text10_var.set(r'0.001')
    text10 = tk.Entry(window, textvariable=text10_var, bd=5).grid(row=9, column=1)
    #
    lable11 = tk.Label(window, text="转换参数", width=15).grid(row=10, column=0)
    text11_var = tk.StringVar()  # 获取text_1输入的值
    text11_var.set(r',,,,,,')
    text11 = tk.Entry(window, textvariable=text11_var, bd=5).grid(row=10, column=1)
    #
    lable12 = tk.Label(window, text="[地块坐标]", width=15).grid(row=11, column=0)
    text12_var = tk.StringVar()  # 获取text_1输入的值
    text12_var.set(r'默认')
    text12 = tk.Entry(window, textvariable=text12_var, bd=5).grid(row=11, column=1)
    # --------------------------------------------------------------------------------
    lable13 = tk.Label(window, text="界址点个数", width=15).grid(row=12, column=0)  # ???
    text13_var = tk.StringVar()  # 获取text_1输入的值
    text13_var.set(r'默认')
    text13 = tk.Entry(window, textvariable=text13_var, bd=5).grid(row=12, column=1)

    #
    lable14 = tk.Label(window, text="地块面积", width=15).grid(row=13, column=0)  # ????
    text14_var = tk.StringVar()  # 获取text_1输入的值
    text14_var.set(r'默认(公顷),保留四位小数')
    text14 = tk.Entry(window, textvariable=text14_var, bd=5).grid(row=13, column=1)

    #
    lable15 = tk.Label(window, text="地块编号", width=15).grid(row=14, column=0)
    text15_var = tk.StringVar()  # 获取text_1输入的值
    text15_var.set(r'默认(1,2,3....)')
    text15 = tk.Entry(window, textvariable=text15_var, bd=5).grid(row=14, column=1)
    #
    lable16 = tk.Label(window, text="项目名称", width=15).grid(row=15, column=0)
    text16_var = tk.StringVar()  # 获取text_1输入的值
    text16_var.set(r'')
    text16 = tk.Entry(window, textvariable=text16_var, bd=5).grid(row=15, column=1)
    #
    lable17 = tk.Label(window, text="面", width=15).grid(row=16, column=0)
    text17_var = tk.StringVar()  # 获取text_1输入的值
    text17_var.set(r'面')
    text17 = tk.Entry(window, textvariable=text17_var, bd=5).grid(row=16, column=1)
    #
    lable18 = tk.Label(window, text="分幅号", width=15).grid(row=17, column=0)
    text18_var = tk.StringVar()  # 获取text_1输入的值
    text18_var.set(r'')
    text18 = tk.Entry(window, textvariable=text18_var, bd=5).grid(row=17, column=1)
    #
    lable19 = tk.Label(window, text="用地性质", width=15).grid(row=18, column=0)
    text19_var = tk.StringVar()  # 获取text_1输入的值
    text19_var.set(r'其他用地')
    text19 = tk.Entry(window, textvariable=text19_var, bd=5).grid(row=18, column=1)
    #

    tk.Button(window, text="打开", width=20, height=1, command=list_save2, bg="Cyan").grid(row=13, column=4)
    tk.Button(window, text="合并", width=20, height=1, command=get_hebing, bg="Cyan").grid(row=15, column=4)

    tk.Button(window, text="转换", width=20, height=1, command=get_save, bg="Green").grid(row=14, column=3)
    tk.Button(window, text="清空列表", width=20, height=1, command=listbox_delete, bg="Red").grid(row=14, column=5)
    #
    listbox.grid(row=0, column=2, rowspan=13, columnspan=6)
    # -------------------------------------------
    window.mainloop()


def daoru():
    now = datetime.datetime.now()

    '''打开选择文件夹对话框'''
    window3 = tk.Toplevel()
    window3.title("勘测定界图斑导入2.0  by: 放放风")
    window3.geometry('470x190+800+200')  # 290 160为窗口大小,+1000 +10 定义窗口弹出时的默认展示位置
    window3.resizable(0, 0)
    window3['background'] = 'DimGray'

    def about():
        tk.messagebox.showinfo('关于', "勘测定界坐标导入1.0\n \n\nby:放放风 2021.01.23 \n更多功能请联系:[email protected]")

    menubar = tk.Menu(window3)
    file_menu = tk.Menu(menubar, tearoff=False)
    menubar.add_command(label='关于', command=about)
    window3.config(menu=menubar)
    r_value = tk.IntVar()

    class Variable:
        def __init__(self):
            self.one = ""
            self.File_path = ""
            self.File_name = ""
            self.Save_path = ""
            self.pnts = None
            self.layer = None
            self.r = None
            self.cp = None
            self.gd_name = None

        def r_print(self):  # 获取单选框值
            self.r = r_value.get()

        def get_gravity_point(self, points):
            """
            @brief      获取多边形的重心点
            @param      points  The points
            @return     The center of gravity point.
            """
            if len(points) <= 2:
                return list()

            area = Decimal(0.0)
            x, y = Decimal(0.0), Decimal(0.0)
            for i in range(len(points)):
                lng = Decimal(points[i][0])
                lat = Decimal(points[i][1])
                nextlng = Decimal(points[i - 1][0])
                nextlat = Decimal(points[i - 1][1])

                tmp_area = (nextlng * lat - nextlat * lng) / Decimal(2.0)
                area += tmp_area
                x += tmp_area * (lng + nextlng) / Decimal(3.0)
                y += tmp_area * (lat + nextlat) / Decimal(3.0)
            x = x / area
            y = y / area
            self.cp = APoint(float(x), float(y))

        def open(self):  # 打开文本
            File_path = filedialog.askopenfilenames(filetypes=[("文本", "txt")], title="选择需要导入的文本")  # 获取需要转换的规划文件绝对路径
            if not File_path:
                tk.messagebox.showinfo('警告', "请选择文本!")
            else:
                self.File_path = File_path

        def formatting(self, path, r):  # 转换
            constant = float(text1_var.get())  # 获取输入框中的常数
            with open(path) as f:  # 打开文本
                p = []
                c = []
                val = f.readlines()  # 读取文本行
                if r == 2:  # 二调
                    val = [x.split(",") for x in val]  # 按,分割列表中的字符
                    for s in val[:-1]:  # 循环列表
                        A = float(s[0]) - constant  # x扣除常数
                        B = float(s[1][:-1])  # y
                        c.append([A, B])
                        p.append(APoint(A, B))  # 添加点Ax,By
                    pnts = numpy.array([m for n in p for m in n], dtype=numpy.float)  # 转一维矩阵
                    self.cp = c
                    self.pnts = pnts
                    self.layer = "二调图斑"  # cad图层

                elif r == 1:  # 规划
                    tb = []  # 列表中J1位置
                    n = []  # 两个j1中间的值
                    text = []  # 所有文本中两个j1中间的值
                    d = []
                    count = 0  # 计数
                    for s in val:  # 循环文本列表
                        if "J1" in s:  # 如果J1在s内
                            tb.append(val.index(s))  # 获取J1在文本中的位置
                    for q in range(int(len(tb) / 2)):  # 循环位置 1,2  3,4  5,6 共3次
                        text.append(val[tb[count]:tb[count + 1]])
                        count += 2
                    for r in text:
                        for w in r:
                            k = w.split(",")
                            A = float(k[4])
                            B = float(k[5]) - constant  # 扣除常数
                            d.append([B, A])
                            n.append(APoint(B, A))
                        p.append(n)
                        c.append(d)
                        n = []
                        d = []
                    self.cp = c
                    self.pnts = p
                    self.layer = "规划图斑"

                elif r == 3:  # 供地,同上
                    tb = []
                    text = []
                    n = []
                    count = 0
                    d = []
                    gd_name = []

                    for s in val:
                        if "@" in s:
                            tb.append(val.index(s))
                            gd_name.append("地块" + s.split(",")[0])
                    self.gd_name = gd_name
                    for q in range(len(tb)):
                        if q < len(tb) - 1:
                            text.append(val[tb[count] + 1:tb[count + 1] - 1])

                            count += 1
                        if q == len(tb) - 1:
                            text.append(val[tb[count] + 1:-1])

                    for r in text:
                        for w in r:
                            k = w.split(",")
                            A = float(k[2])
                            B = float(k[3]) - constant
                            n.append(APoint(B, A))
                            d.append([B, A])
                        p.append(n)
                        c.append(d)
                        n = []
                        d = []
                    self.cp = c
                    self.pnts = p
                    self.layer = "供地图斑"

    myobject = Variable()

    def map():
        myobject.open()
        # 连接cad
        acad = Autocad(create_if_not_exists=True)
        if 5 < now.hour < 10:
            acad.prompt('早安,打工人!')
        elif 10 < now.hour < 14:
            acad.prompt('午安,打工人!')
        elif 14 < now.hour < 18:
            acad.prompt('下午好,打工人!')
        elif now.hour > 18:
            acad.prompt('晚安,打工人!')

        for path in myobject.File_path:
            myobject.formatting(path, myobject.r)
            name = path.split("/")[-1][:-4]
            # 设定图层
            layerobj = acad.ActiveDocument.Layers.Add(myobject.layer)
            acad.ActiveDocument.ActiveLayer = layerobj
            # 多段线颜色
            ClrNum = 1
            layerobj.color = ClrNum
            # 画线
            if myobject.r == 3 or myobject.r == 1:
                for pnts in myobject.pnts:
                    pnts = numpy.array([m for n in pnts for m in n], dtype=numpy.float)
                    pnts = Autocad.aDouble(pnts)
                    pline_obj = acad.model.AddPolyLine(pnts)
                    pline_obj.Closed = True  # 闭合多段线
                if myobject.r == 1:
                    for c in myobject.cp:
                        myobject.get_gravity_point(c)
                        text = acad.model.AddText("{0}".format(name), myobject.cp, 1.5)
                if myobject.r == 3:
                    n = 0
                    for c in myobject.cp:
                        myobject.get_gravity_point(c)
                        text = acad.model.AddText("{0}".format(myobject.gd_name[n]), myobject.cp, 1.5)
                        n += 1
                    n = 0
            else:
                pnts = Autocad.aDouble(myobject.pnts)
                pline_obj = acad.model.AddPolyLine(pnts)
                pline_obj.Closed = True  # 闭合多段线
                myobject.get_gravity_point(myobject.cp)
                text = acad.model.AddText("{0}".format(name), myobject.cp, 1.5)

        # 保存
        acad.ActiveDocument.Application.preferences.OpenSave.AutoSaveInterval = 0.51
        tk.messagebox.showinfo('提示', "转换成功,请检查数据")

    tk.Radiobutton(window3, text='规划坐标', variable=r_value, value=1, command=myobject.r_print, width=12).grid(row=1,
                                                                                                             column=0)
    tk.Radiobutton(window3, text='二调坐标', variable=r_value, value=2, command=myobject.r_print, width=12).grid(row=2,
                                                                                                             column=0)
    tk.Radiobutton(window3, text='供地坐标', variable=r_value, value=3, command=myobject.r_print, width=12).grid(row=3,
                                                                                                             column=0)

    lable1 = tk.Label(window3, text="[  扣除带号  ]", width=15).grid(row=0, column=0)
    text1_var = tk.StringVar()  # 获取text_1输入的值
    text1_var.set(r'40000000')
    text1 = tk.Entry(window3, textvariable=text1_var, bd=5).grid(row=0, column=1)

    tk.Button(window3, text="导入cad", width=15, height=1, command=map, bg="Silver").grid(row=5, column=0)

    text20 = tk.Text(window3, width=50, height=12)
    text20.grid(row=1, column=1, rowspan=5, columnspan=2)
    text20.tag_config("tag_1", backgroun="yellow", foreground="red")

    text20.insert("insert",
                  "1.导入时打开cad\n\n2.规划:cad中地块编号为文本名称;支持导入合并坐标\n\n"
                  "3.二调:同上,不支持合并坐标导入\n\n"
                  "4.供地:cad中地块编号为【地块】+ 地块编号\n\n")

    text20.insert("end", "5.更多功能请联系:\[email protected]", "tag_1")

    window3.mainloop()


tk.Button(window0, text="1-选择图斑", width=20, height=1, command=myobj.Select_element, bg="Azure").grid(row=7, column=1)
lableA1 = tk.Label(window0, text="[规划、二调属性设置]", width=45).grid(row=1, column=0, columnspan=2)

lableA2 = tk.Label(window0, text="[  带  号  ]", width=20).grid(row=2, column=0)
textA2_var = tk.StringVar()  # 获取text_1输入的值
textA2_var.set(r'40000000')
textA2 = tk.Entry(window0, textvariable=textA2_var, bd=5).grid(row=2, column=1)

lableA3 = tk.Label(window0, text="[文本后缀]", width=20).grid(row=4, column=0)
textA3_var = tk.StringVar()  # 获取text_1输入的值
textA3_var.set(r'(规划)')
textA3 = tk.Entry(window0, textvariable=textA3_var, bd=5).grid(row=4, column=1)

lableA4 = tk.Label(window0, text="[小数位数]", width=20).grid(row=3, column=0)
textA4_var = tk.StringVar()  # 获取text_1输入的值
textA4_var.set(r'3')
textA4 = tk.Entry(window0, textvariable=textA4_var, bd=5).grid(row=3, column=1)

cjip = tk.PhotoImage(file="./help/pic_01.gif")
tk.Label(window0, image=cjip, height=300, width=300).grid(row=8, column=0, columnspan=2)

tk.Button(window0, text="2-规划坐标", width=20, height=1, command=plane, bg="Azure").grid(row=5, column=0)
tk.Button(window0, text="规划合并", width=20, height=1, command=plan_merge, bg="Azure").grid(row=5, column=1)
tk.Button(window0, text="3-二调坐标", width=20, height=1, command=two_coordinate, bg="Azure").grid(row=6, column=0)
tk.Button(window0, text="4-供地坐标", width=20, height=1, command=Gd, bg="Azure").grid(row=7, column=0)
tk.Button(window0, text="导入CAD", width=20, height=1, command=daoru, bg="Azure").grid(row=6, column=1)
window0.mainloop()

你可能感兴趣的:(测绘,python)