I am trying to display a pandas DataFrame in tkinter python and all of the columns are misaligned.
First this function takes these 4 columns from my log table and converts it into DataFrame
def show_log():
df = pandas.read_sql("SELECT id, user_id, book_id, action FROM library.log LIMIT 10", con=mydb)
blankIndex = [''] * len(df)
df.index = blankIndex
return df
Then this function creates a tkinter label with the dataframe
def show_log(self):
self.label_show_log = tk.Label(self.master, text=fu.show_log(), borderwidth=2, relief="groove")
self.label_show_log.pack()
This is the tkinter output I get - and it's ugly:
I want to make all of the columns and the data evenly aligned! Thank you for any help! :)
CodePudding user response:
I use pandastable to display dataframes in tkinter
Install: pip install pandastable
Code:
import pandas as pd
from pandastable import Table
#Create DataFrame class
class DataFrameTable(Frame):
def __init__(self, parent=None, df=pd.DataFrame()):
super().__init__()
self.parent = parent
self.pack(fill=BOTH, expand=True)
self.table = Table(
self, dataframe=df,
showtoolbar=False,
showstatusbar=True,
editable=False)
self.table.show()
#Tkinter window
root = Tk()
#Show Table
DataFrameTable(root, your_dataframe)
root.mainloop()
CodePudding user response:
One solution is to use the tabulate
library, which can format a pandas DataFrame as a table with specified alignment and padding. You can install it by running pip install tabulate
. Then, modify your show_log
function to the following:
def show_log(self):
df = fu.show_log()
table = tabulate(df, headers='keys', tablefmt='grid', showindex=False)
self.label_show_log = tk.Label(self.master, text=table, borderwidth=2, relief="groove")
self.label_show_log.pack()
This will display the DataFrame as a table with columns and data aligned.