Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

python - Pretty print data in tkinter Label

I have following sample data

data=[(1,'JohnCena','Peter',24,74),
      (2,'James','Peter',24,70),
      (3,'Cena','Peter',14,64),
      (14,'John','Mars',34,174)]

I want to print it on python gui in a beutiful tabular way on tkinter output window. I am using tabulate package to print. Here is my function

def display_date():
    disp=pd.DataFrame(data,columns=['id','first name','last name','age','marks'])
    newwin = Toplevel(right_frame)
    newwin.geometry('500x400')
    Label_data=Label(newwin,text=tabulate(disp, headers='keys',tablefmt='github',showindex=False))
    Label_data.place(x=20,y=50)

You can see the output is not symmetric. I want a beautiful symmetric tabular output. How can I do that

Here is the output image

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Question: tabulate output, displayed in a tk.Label, without to distort the data.


As pointed out in the comments this can be done using a monospaced font.
You have to use the following Label options,

justify=tk.LEFT
anchor='nw'

to justify the table left, and stick it to top left position.


Reference:


enter image description here

import tkinter as tk
from tabulate import tabulate

data = [('id', 'first name', 'last name', 'age', 'marks'),
        (1, 'JohnCena', 'Peter', 24, 74),
        (2, 'James', 'Peter', 24, 70),
        (3, 'Cena', 'Peter', 14, 64),
        (14, 'John', 'Mars', 34, 174)
        ]


class TabulateLabel(tk.Label):
    def __init__(self, parent, data, **kwargs):
        super().__init__(parent, 
                         font=('Consolas', 10), 
                         justify=tk.LEFT, anchor='nw', **kwargs)

        text = tabulate(data, headers='firstrow', tablefmt='github', showindex=False)
        self.configure(text=text)


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        TabulateLabel(self, data=data, bg='white').grid(sticky='ew')

if __name__ == "__main__":
    App().mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...