設備管理系統-基於Tkinter的小案例

基於Tkinter,做了一個簡易的設備管理系統。

文件格式

檢驗文件.txt 文件格式如下:
在這裏插入圖片描述

狀態獲取.txt 文件格式如下:

機器名稱:測試4號	   220V	   2.5A

代碼如下

import tkinter as tk
import tkinter.messagebox as msg
import re


Machines_list = ['機器名稱', '額定電壓', '額定電流', '故障原因', '故障名稱', '故障地點']
# 檢驗文件路徑
filepath = '.\檢驗文件.txt'
# 狀態文件
infile = '.\狀態獲取.txt'

str_print = "{}\t {}V\t {}A\t {}\t {}\t {}\n"

# 字體設置
font = ('Arial', 14)


def clear():
    # 清空框架
    for widget in frame.winfo_children():
        widget.destroy()


def write_information(entrys):
    """
    信息寫入
    Arguments:
        frame {[type]} -- [description]
        entrys {[type]} -- [description]
    """
    infos = []
    for entry in entrys:
        infos.append(entry.get())

    # 解包
    n_g, u_g, i_g, h_g, r_g, k_g = infos
    with open(filepath, 'a', encoding='utf-8') as file_object:
        file_object.write(str_print.format(n_g, u_g, i_g, h_g, r_g, k_g))

    # 提示保存成功
    msg.showinfo('success', '保存成功')


def input_information():
    """
    信息輸入
    """
    clear()
    # 要保存的信息
    entrys = []
    # 錄入信息
    for row, info in enumerate(Machines_list):
        tk.Label(frame, text=info, font=font).grid(row=row, column=0)

        entry = tk.Entry(frame, font=font)
        entry.grid(row=row, column=1)
        entrys.append(entry)

    # 確認按鈕
    btn_comfirm = tk.Button(
        frame, text='錄入', command=lambda: write_information(entrys))
    btn_comfirm.grid(row=6, column=2)


def show_information():
    """
    展示機器信息
    """
    clear()
    str_print = "機器名稱:{}\t額定電壓:{}\t額定電流:{}\t故障原因:{}\t故障名稱:{}\t故障地點:{}"
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        lines = lines[1:]
        for row, line in enumerate(lines):
            # 跳過空行
            line = line.strip()
            if not line:
                continue
            infos = line.split('\t')
            tk.Label(frame, text=str_print.format(
                infos[0], infos[1], infos[2], infos[3], infos[4], infos[5]), font=font).grid(row=row, column=0)


def read_information(entry, res_frame):
    # 清空res_frame
    for widget in res_frame.winfo_children():
        widget.destroy()

    # 查詢關鍵字
    key = entry.get()
    flag = False
    row = 2
    str_print = "{}\t {}\t {}\t {}\t {}\t {}"
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        lines = lines[1:]
        for line in lines:
            infos = line.split('\t')
            infos = list(map(lambda x: x.strip(), infos))
            if key in infos:
                tk.Label(res_frame, text=str_print.format(
                    infos[0], infos[1], infos[2], infos[3], infos[4], infos[5]), font=font).grid(row=row, column=0)
                flag = True
                row += 1
        if flag:
            # 提示查詢成功
            msg.showinfo('success', '成功檢索到您輸入的機器信息')
        else:
            msg.showinfo('failed', '未檢索到您輸入的機器信息')


def search_information():
    clear()

    tk.Label(frame, text='請輸入需要查詢的關鍵字', font=font).grid(row=0, column=0)
    entry = tk.Entry(frame, font=font)
    entry.grid(row=0, column=1)

    # 查詢結果顯示框架
    res_frame = tk.Frame(frame, height=400, width=400)
    res_frame.grid(row=2, column=1)
    # 確認按鈕
    btn_comfirm = tk.Button(
        frame, text='查詢', command=lambda: read_information(entry, res_frame))
    btn_comfirm.grid(row=1, column=1)


def drop_information(entry, res_frame):
    # 清空res_frame
    for widget in res_frame.winfo_children():
        widget.destroy()

    # 刪除關鍵字
    key = entry.get()
    flag = False
    row = 2

    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    with open(filepath, 'w', encoding='utf-8') as f:
        for i, line in enumerate(lines):
            # 寫入表頭
            if i < 1:
                f.write(line)
                continue

            infos = line.split('\t')
            if key in infos:
                tk.Label(res_frame, text=str_print.format(
                    infos[0], infos[1], infos[2], infos[3], infos[4], infos[5]), font=font).grid(row=row, column=0)
                flag = True
                row += 1
                continue
            # 寫入
            f.write(line)

        if flag:
            # 提示查詢成功
            msg.showinfo('success', '成功刪除')
        else:
            msg.showinfo('failed', '刪除失敗,未檢索到您輸入的機器信息')


def delete_information():
    """
    刪除信息
    """
    clear()

    tk.Label(frame, text='請輸入需要刪除的信息關鍵字', font=font).grid(row=0, column=0)
    entry = tk.Entry(frame, font=font)
    entry.grid(row=0, column=1)

    # 刪除結果顯示框架
    res_frame = tk.Frame(frame, height=400, width=400)
    res_frame.grid(row=2, column=1)
    # 確認按鈕
    btn_comfirm = tk.Button(
        frame, text='刪除', command=lambda: drop_information(entry, res_frame))
    btn_comfirm.grid(row=1, column=1)


def save_information(entrys, line_numbers):

    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    # 保存文件
    str_print = "{}\t {}\t {}\t {}\t {}\t {}"
    with open(filepath, 'w', encoding='utf-8') as f:
        # 表頭寫入
        f.write(lines[0])
        lines = lines[1:]
        for i, line in enumerate(lines):
            if i in line_numbers:
                index = line_numbers.index(i)
                row_entory = entrys[index]
                row = list(map(lambda x: x.get(), row_entory))
                n_g, u_g, i_g, h_g, r_g, k_g = row
                f.write(str_print.format(n_g, u_g, i_g, h_g, r_g, k_g))

            else:
                f.write(line)

    msg.showinfo('success', '修改已完成')
    # 展示信息
    show_information()


def modify(entry, res_frame):
    # 清空res_frame
    for widget in res_frame.winfo_children():
        widget.destroy()

    # 頂頭
    for col, info in enumerate(Machines_list):
        tk.Label(res_frame, text=info, font=font).grid(row=0, column=col)

    # 修改關鍵字
    key = entry.get()
    flag = False
    row = 1

    # 要修改的內容
    entrys = []
    # 在文件中的行數
    line_numbers = []
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        lines = lines[1:]
        for i, line in enumerate(lines):
            infos = line.split('\t')
            if key in infos:
                text = tk.StringVar()
                text.set("在文件中的行數{}".format(i))
                line_numbers.append(i)
                entry = tk.Entry(
                    res_frame, textvariable=text, width=10, font=font)
                # 保存每行entory
                row_entory = []
                # 展示查詢內容
                for col, info in enumerate(infos):
                    text = tk.StringVar()
                    text.set(info)
                    entry = tk.Entry(
                        res_frame, textvariable=text, width=10, font=font)
                    entry.grid(row=row, column=col)
                    row_entory.append(entry)

                flag = True
                row += 1
                entrys.append(row_entory)
        if not flag:
            # 提示沒有信息
            msg.showinfo('failed', '未檢索到您輸入的機器信息')

   # 確認按鈕
    btn_comfirm = tk.Button(
        res_frame, text='確認', command=lambda: save_information(entrys, line_numbers))
    btn_comfirm.grid(row=row, column=1)


def modify_information():
    """
    修改
    """
    clear()

    tk.Label(frame, text='請輸入需要修改的機器信息', font=font).grid(row=0, column=0)
    entry = tk.Entry(frame, font=font)
    entry.grid(row=0, column=1)

    # 查詢結果顯示框架
    res_frame = tk.Frame(frame, height=400, width=400)
    res_frame.grid(row=2, column=0)

    # 按鈕
    btn_comfirm = tk.Button(
        frame, text='修改', command=lambda: modify(entry, res_frame))
    btn_comfirm.grid(row=1, column=1)


def loadDatadet():
    # 加載故障文件
    f = open(infile, "r", encoding='utf-8')
    source_in_line = f.readlines()
    dataset = []
    for line in source_in_line:
        temp = re.split('\t|:', line)[1:]
        dataset.append(temp)
    return dataset


def trouble():
    """
    故障檢索
    """
    clear()

    m_list = loadDatadet()
    n_g, u_g, i_g = m_list[0]
    u_g = re.findall('\d+', u_g)[0]
    i_g = re.findall('\d+', i_g)[0]
    u_g = float(u_g)
    i_g = float(i_g)

    str_print_1 = "機器名稱:{}\t實時電壓:{}V\t實時電流:{}A"
    tk.Label(frame, text='實時數據', font=font).grid(row=0, column=0)
    tk.Label(frame, text=str_print_1.format(n_g, u_g, i_g),
             font=font).grid(row=1, column=0)

    tk.Label(frame, text='額定數據', font=font).grid(row=2, column=0)
    tk.Label(frame, text='檢索結果', font=font).grid(row=2, column=1)

    row = 3
    flag = False
    str_print_2 = "機器名稱:{}\t額定電壓:{}V\t額定電流:{}A"
    with open(filepath, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        lines = lines[1:]
        for line in lines:
            infos = line.split('\t')
            # 跳過空行或非對應機器
            if not line.strip() or n_g != infos[0]:
                continue
            u_1 = re.findall('\d+', infos[1])[0]
            i_1 = re.findall('\d+', infos[2])[0]
            u_1 = float(u_1)
            i_1 = float(i_1)
            # 校驗
            text = ''
            if u_g * 0.95 <= u_1 <= u_g * 1.05:
                flag = True
                text = text+"\t電壓狀況良好"
            else:
                text = text+"\t電壓出現故障"

            if i_g * 0.95 <= i_1 <= i_g * 1.05:
                flag = True
                text = text+"\t電流狀況良好"
            else:
                text = text+"\t電流出現故障"

            tk.Label(frame, text=str_print_2.format(infos[0], u_1, i_1),
                     font=font).grid(row=row, column=0)
            tk.Label(frame, text=text, font=font).grid(row=row, column=1)
            row += 1

    if not flag:
        # 提示信息
        msg.showinfo('info', '沒有檢索到故障信息')
    else:
        msg.showinfo('info', '故障信息檢索完畢')


# 實例化窗口
root = tk.Tk()
root.title("設備管理文件")
# 大小設置
root.geometry('1000x700')

lable = tk.Label(root, text="歡迎進入設備管理系統,2020年6月出品",
                 bg="blue", fg="red", font=("黑體", 20))
lable.pack()

# 框架
frame = tk.Frame(root, height=600, width=1000)
frame.pack()


# 創建頂級菜單
menu = tk.Menu(root)
# 基礎操作
basic_menu = tk.Menu(menu)
menu.add_cascade(label='基礎操作', menu=basic_menu)
basic_menu.add_command(label='錄入本部機器信息', command=input_information)
basic_menu.add_command(label='顯示全部機器信息', command=show_information)
basic_menu.add_command(label='查詢錄入機器信息', command=search_information)
basic_menu.add_command(label='刪除錄入機器信息', command=delete_information)
basic_menu.add_command(label='修改錄入機器信息', command=modify_information)

# 故障檢索
malfunction = tk.Menu(menu)
menu.add_cascade(label='故障檢索', menu=malfunction)
malfunction.add_command(label='開始檢索', command=trouble)


# 顯示菜單
root.config(menu=menu)
# 主窗口循環
root.mainloop()

運行效果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章