Python tkinter标签中的漂亮打印数据

Python tkinter标签中的漂亮打印数据,python,user-interface,tkinter,label,tabulate,Python,User Interface,Tkinter,Label,Tabulate,我有以下样本数据 data=[(1,'JohnCena','Peter',24,74), (2,'James','Peter',24,70), (3,'Cena','Peter',14,64), (14,'John','Mars',34,174)] 我想在tkinter输出窗口上以一种有用的表格方式在python gui上打印它。我正在使用软件包打印。 这是我的功能 def display_date(): disp=pd.DataFrame(data

我有以下样本数据

data=[(1,'JohnCena','Peter',24,74),
      (2,'James','Peter',24,70),
      (3,'Cena','Peter',14,64),
      (14,'John','Mars',34,174)]
我想在tkinter输出窗口上以一种有用的表格方式在python gui上打印它。我正在使用软件包打印。 这是我的功能

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)
您可以看到输出是不对称的。我想要一个漂亮的对称表格输出。我该怎么做

这是输出

问题
制表
输出,显示在
tk.标签
中,不会扭曲数据


正如评论中指出的,这可以使用
单间距字体

您必须使用以下
标签
选项

justify=tk.LEFT
anchor='nw'
将表格左对齐,并将其粘贴到左上角位置


参考资料:



尝试使用单间距字体<代码>标签(…,font='Consolas')
我认为您需要一些单空格字体(意味着所有字母都具有相同的宽度)来正确对齐
制表所产生的列。例如,在标签内使用参数
font='Roboto Mono'
。替代设计方案:为每个单元格创建一个条目对象,并将其排列在网格中。当您有GUI时,不需要使用文本来定位数据。
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()