首页 > 解决方案 > 如何使用 python tkinter 为我的表格制作边框?

问题描述

显然,我的应用程序可以显示 excel 文件,但是表格没有边框有点乱。

import pandas as pd
import xlrd
import tkinter as tk
from tkinter import*
from tkinter import ttk, filedialog

root = tk.Tk()
root.title("My Application")
width = 1000
height = 500

def browseFile():
    global workbook, copyWorkbook, excel_file, sheetName, worksheet, df_table

    fileName = filedialog.askopenfilename(initialdir = '/', title = 'New File', filetypes = (('excel file', '.xlsx'), ('excel file', '.xls'), ('all files', '*.*')))
    excel_file = pd.ExcelFile(fileName)
    workbook = xlrd.open_workbook(fileName)
    sheetCount = workbook.nsheets

    sheetName = []
    tab = []
    for x in range(workbook.nsheets):
        tab.append(ttk.Frame(tabControl))
        sheetName = workbook.sheet_names()
        tabControl.add(tab[x], text = sheetName[x])
        df_table = excel_file.parse(sheetName[x])
        lblTable = Label(tab[x], text = df_table.to_string(index = False)).pack()

toolbar = Frame(root)
btnOpen = Button(toolbar, text = "Open", command = browseFile).pack(side = LEFT)
btnQuit = Button(toolbar, text = "Quit", command = root.quit).pack(side = RIGHT)
toolbar.pack(side = TOP, fill = X)

tabControl = ttk.Notebook(root)
tabHome = ttk.Frame(tabControl)
tabControl.pack(expand = 1, fill = 'both', side = LEFT)

root.mainloop()

我尝试了可以​​显示带边框的表格的搜索语句,但没有找到结果。如何为表格添加边框?可以加边框吗?如果没有,我可以使用什么其他方法?

标签: python-3.xtkinter

解决方案


问题

您的问题是,您的代码将整个数据框放入一个Label小部件中。当我尝试在此标签周围设置边框时,它出现在整个数据框周围,而不是每个单元格周围。

我的解决方案

我对此的解决方案是遍历所有行并为每个单元格创建一个单独的Label小部件,为每个单元格提供自己的边框。.grid()然后我使用而不是组织它们.pack()。对于边框,我使用了设置borderwidth=2, relief="ridge",但您可以选择其他

我还添加了一个功能,将每列的宽度设置为其最长值,以防止标签的内容溢出。

我没有包含任何包含行和列标题的内容,但是您替换i.pop(0)i[0]更改header=none应该添加此功能。

修改后的代码

我只 for 在您的函数中包含了循环, browseFile() 因为我没有对您的其余代码进行任何更改。

for x in range(workbook.nsheets):
    tab.append(ttk.Frame(tabControl))
    sheetName = workbook.sheet_names()
    tabControl.add(tab[x], text = sheetName[x])
    df_table = excel_file.parse(sheetName[x], header=None) # header=None stops the first line of the data table being used as the column header, making it appear in the data table

    # Iterates through each row, creating a Label widget for each cell on that row.
    for i in df_table.itertuples(): 
        i=list(i) # Converts the row to a more helpful list format
        row = i.pop(0) # pop returns value at position, then removes it, as we don't wan't first value of tuple (row number) in spreadsheet
        for j in range(len(i)):
            # Next two lines get the current column in a list format and convert all items to a string, in order to determine the longest item to make all label widgets the correct width.
            current_column = list(df_table.iloc[:, j])
            for k in range(len(current_column)): current_column[k] = str(current_column[k])
            # Makes label widget
            lbl = Label(tab[x], text = i[j], borderwidth=2, relief="ridge", width=len(max(current_column, key=len)), justify=LEFT).grid(row=row, column=j+1)

PS:我真的很喜欢解决这个问题。谢谢提问!


推荐阅读