首页 > 解决方案 > 在 Listbox tk Python 中查看 Excel 数据

问题描述

所以我正在练习制作一个将数据保存在excel文件中的输入表。

from tkinter import *
import pandas as pd
from openpyxl import load_workbook


def add_data():
    path = 'phonebook.xlsx'
    df1 = pd.read_excel(path)
    SeriesA = df1['First Name']
    SeriesB = df1['Last Name']
    SeriesC = df1['Address']
    SeriesD = df1['Contact Number']
    A = pd.Series(firstname.get())
    B = pd.Series(lastname.get())
    C = pd.Series(address.get())
    D = pd.Series(contactnumber.get())
    SeriesA = SeriesA.append(A)
    SeriesB = SeriesB.append(B)
    SeriesC = SeriesC.append(C)
    SeriesD = SeriesD.append(D)
    df2 = pd.DataFrame({"First Name":SeriesA, "Last Name":SeriesB, "Address":SeriesC, "Contact Number":SeriesD})
    df2.to_excel(path, index=False)
    firstname.delete(0, END)
    lastname.delete(0, END)
    address.delete(0, END)
    contactnumber.delete(0, END)


def view():
    file = "phonebook.xlsx"
    wb = load_workbook(file, data_only=True)
    ws = wb.active
    r = 0
    for row in ws:
        c = 0
        for cell in row:
            e = Label(frame2, text=cell.value).grid(row=r, column=c)
            lstdata.insert(END, e)
            c += 1
        r += 1

if __name__=='__main__':
    master = Tk()
    frame1 = Frame(master, bd=10)
    frame1.grid()
    frame2 = Frame(master, bd=10)
    frame2.grid()

    Label(frame1, text="First Name").grid(row=0)
    Label(frame1, text="Last Name").grid(row=1)
    Label(frame1, text="Address").grid(row=2)
    Label(frame1, text="Contact Number").grid(row=3)

    firstname = Entry(frame1)
    lastname = Entry(frame1)
    address = Entry(frame1)
    contactnumber = Entry(frame1)
    firstname.grid(row=0, column=1)
    lastname.grid(row=1, column=1)
    address.grid(row=2, column=1)
    contactnumber.grid(row=3, column=1)


    scrollbar = Scrollbar(frame2)
    scrollbar.grid(row=1, column=1)
    lstdata = Listbox(frame2, yscrollcommand=scrollbar.set, selectmode='multiple')
    lstdata.grid(row=1, column=0, sticky='nsew')
    scrollbar.config(command=lstdata.xview)

    Button(frame1, text='Add', command=add_data).grid(row=4, column=0, pady=5)
    Button(frame1, text='View', command=view).grid(row=4, column=1, pady=5)
    Button(frame1, text='Quit', command=master.quit).grid(row=4, column=3, pady=5)
    master.mainloop()

以上是我的报名表代码。但是当我单击“查看”按钮时。excel文件中的数据不在列表框中,而是在整个框架中混合

这是我在单击 View button之前单击View button 时的输出。点击查看按钮后

我希望你能帮助我。谢谢

标签: pythonpython-3.xtkinter

解决方案


推荐阅读