如何在我的 python 应用程序中添加编辑和删除功能来编辑或删除整个 excel 行(不仅仅是值,还有行本身)?

问题描述 投票:0回答:0

这是我的代码:

from os import path
import tkinter as tk
from tkinter import ttk
import openpyxl


root = tk.Tk()
root.title("School Accounting System")
root.geometry("901x365")

style = ttk.Style(root)
root.tk.call("source", "forest-light.tcl")
root.tk.call("source", "forest-dark.tcl")
style.theme_use("forest-dark")

def load_data():
    path = "accounts.xlsx"
    workbook = openpyxl.load_workbook(path)
    sheet = workbook.active

    list_values = list(sheet.values)
    print(list_values)
    for col_name in list_values[0]:
        treeview.heading(col_name, text=col_name)

    list_values = list(sheet.values)
    print(list_values)
    for col_account in list_values[0]:
        treeview.heading(col_account, text=col_account)

    list_values = list(sheet.values)
    print(list_values)
    for col_payment in list_values[0]:
        treeview.heading(col_payment, text=col_payment)

    for value_tuple in list_values[1:]:
        treeview.insert('', tk.END, values=value_tuple)

def save_data():
    name = name_entry.get()
    account = account_entry.get()
    payment = payment_entry.get()

    if name and account and payment:
        # Calculate the balance
        try:
            balance = float(account) - float(payment)
        except ValueError:
            balance = ""

        # Insert row into Excel sheet
        path = "accounts.xlsx"
        workbook = openpyxl.load_workbook(path)
        sheet = workbook.active
        row_values = [name, account, payment, balance]
        sheet.append(row_values)
        workbook.save(path)

        # Insert row into treeview
        treeview.insert('', tk.END, values=row_values)

        # Clear the values
        name_entry.delete(0, "end")
        name_entry.insert(0, "Name")
        account_entry.delete(0, "end")
        account_entry.insert(0, "Account")
        payment_entry.delete(0, "end")
        payment_entry.insert(0, "Payment")


def toggle_mode():
    if mode_switch.instate(["selected"]):
        style.theme_use("forest-light")
    else:
        style.theme_use("forest-dark")
    
def on_treeview_click(event):
    item = treeview.focus()
    values = treeview.item(item)['values']
    name_entry.delete(0, 'end')
    account_entry.delete(0, 'end')
    payment_entry.delete(0, 'end')
    if values:
        name_entry.insert(0, values[0])
        account_entry.insert(0, values[3])
        payment_entry.insert(0, values[2])

def update_data():
    name = name_entry.get()
    account = account_entry.get()
    payment = payment_entry.get()

    if name and account and payment:
        # Calculate the balance
        try:
            balance = float(account) - float(payment)
        except ValueError:
            balance = ""

        # Insert or update row in Excel sheet
        path = "accounts.xlsx"
        workbook = openpyxl.load_workbook(path)
        sheet = workbook.active
        row_values = [name, account, payment, balance]

        # Check if the name already exists in the sheet
        name_exists = False
        for row in sheet.iter_rows(min_row=2, values_only=True):
            if row[0] == name:
                row[1] = account
                row[2] = payment
                row[3] = balance
                name_exists = True
                break

        if not name_exists:
            sheet.append(row_values)

        workbook.save(path)

        # Insert row into treeview
        treeview.insert('', tk.END, values=row_values)

        # Clear the values
        name_entry.delete(0, "end")
        name_entry.insert(0, "Name")
        account_entry.delete(0, "end")
        account_entry.insert(0, "Account")
        payment_entry.delete(0, "end")
        payment_entry.insert(0, "Payment")

def refresh_data(mode):
    # Clear the treeview
    treeview.delete(*treeview.get_children())

    # Load the data from the Excel sheet
    path = "accounts.xlsx"
    workbook = openpyxl.load_workbook(path)
    sheet = workbook.active
    rows = sheet.iter_rows(min_row=2, values_only=True)

    # Populate the treeview with the data
    for row in rows:
        if mode == "A" or (mode == "B" and row[3] < 1000):
            treeview.insert("", tk.END, tags=row[0], values=row[1:])
            # set the row number as a tag for the treeview item
            item = treeview.tag_has(row[0])
            if item:
                treeview.item(item, tags=(row[0], row[3]))
    # Save the changes to the workbook
    workbook.save(path)

def delete_data():
    # Insert or update row in Excel sheet
    path = "accounts.xlsx"
    workbook = openpyxl.load_workbook(path)
    sheet = workbook.active

    # get the selected items from the treeview
    selection = treeview.selection()
    for item in selection:
        # extract the row number from the treeview item tag
        tags = treeview.item(treeview.focus(), 'tags')
        if tags:
            row = int(treeview.item(treeview.focus(), 'tags')[0])
            # delete the row from the sheet
            sheet.delete_rows(row)
            # delete the item from the treeview
            treeview.delete(item)

    # save the changes to the workbook
    workbook.save('accounts.xlsx')



frame = ttk.Frame(root)
frame.pack(fill="both", expand=True)

widgets_frame = ttk.LabelFrame(frame, text="Enter Student Data")
widgets_frame.grid(row=0, column=0, padx=10, pady=10)

name_entry = ttk.Entry(widgets_frame)
name_entry.insert(0, "Name")
name_entry.bind("<FocusIn>", lambda e: name_entry.delete('0', 'end'))
name_entry.bind("<FocusOut>", lambda e: refresh_data())
name_entry.grid(row=0, column=0, padx=5, pady=(0, 5), sticky="ew")

account_entry = ttk.Entry(widgets_frame)
account_entry.insert(0, "Account")
account_entry.bind("<FocusIn>", lambda e: account_entry.delete('0', 'end'))
account_entry.bind("<FocusOut>", lambda e: refresh_data())
account_entry.grid(row=1, column=0, padx=5, pady=5, sticky="ew")

payment_entry = ttk.Entry(widgets_frame)
payment_entry.insert(0, "Payment")
payment_entry.bind("<FocusIn>", lambda e: payment_entry.delete('0', 'end'))
payment_entry.bind("<FocusOut>", lambda e: refresh_data())
payment_entry.grid(row=2, column=0, padx=5, pady=5, sticky="ew")

button = ttk.Button(widgets_frame, text="Save Data", command=save_data)
button.grid(row=4, column=0, padx=5, pady=5, sticky="nsew")

button = ttk.Button(widgets_frame, text="Update Data", command=save_data)
button.grid(row=5, column=0, padx=5, pady=5, sticky="nsew")

button = ttk.Button(widgets_frame, text="Refresh Data", command=refresh_data)
button.grid(row=6, column=0, padx=5, pady=5, sticky="nsew")

button = ttk.Button(widgets_frame, text="Delete Data", command=delete_data)
button.grid(row=7, column=0, padx=5, pady=5, sticky="nsew")

separator = ttk.Separator(widgets_frame)
separator.grid(row=8, column=0, padx=(20, 10), pady=10, sticky="ew")

mode_switch = ttk.Checkbutton(
    widgets_frame, text="Mode", style="Switch", command=toggle_mode)
mode_switch.grid(row=9, column=0, padx=5, pady=10, sticky="nsew")

treeFrame = ttk.Frame(frame, width=700, height=300)
treeFrame.grid(row=0, column=1, padx=5, pady=10, sticky="nsew")
treeFrame.grid_propagate(True)

treeScroll = ttk.Scrollbar(treeFrame)
treeScroll.pack(side="right", fill="y")

cols = ("Student Name", "Account", "Payment", "New Balance")
treeview = ttk.Treeview(treeFrame, show="headings",
                        yscrollcommand=treeScroll.set, columns=cols, height=13)
treeview.column("Student Name", width=200)
treeview.column("Account", width=150)
treeview.column("Payment", width=150)
treeview.column("New Balance", width=150)
treeview.pack(fill="both", expand=True)
treeview.bind("<ButtonRelease-1>", on_treeview_click)
treeScroll.config(command=treeview.yview)

load_data()

# Add the copyright label below the frame
copyright_label = tk.Label(root, text="Copyright © 2023 | Jelmar Orapa")
copyright_label.pack(side="bottom")

# Set the weight of the rows and columns to 1, so they expand to fill the available space
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=1)

root.mainloop()

我不是真正的程序员我只是从任何地方废弃代码并尝试构建一个应用程序。这个在我们的小学校里会有用。

正如您在我的代码中看到的,我已经有一个名为 update_data() 和 delete_data() 的函数,但是,当我单击“删除数据”按钮时,什么也没有发生,当我单击“更新数据”时,它会创建一个新数据在新的一行中。

我想要完成的是在我的

onclick_treeview_click(event)

被聚焦/选择/点击的树视图项目;可以通过 update_data() 和 delete_data() 函数编辑或删除它所在的整行。

python excel openpyxl delete-row
© www.soinside.com 2019 - 2024. All rights reserved.