Python 中布局文本的最佳模块

Best Module to Layout Text in Python

我正在寻找一个程序来输出一堆(大约 30 个)框,如下图所示:

我已经研究了几个星期,我认为可以在 PyQT 中使用 QTableWidget 以图形化的方式布置文本,但我现在意识到学习这样一个简单的任务太难了,必须有是一个更快的方法。所以我现在正在考虑传递给 Tkinter,或者可能只是使用像 PyCairo 这样的绘图模块来绘制信息,然后才将每个图像放在 PyQT 界面中。整理绘图模块中的所有定位比学习如何在 PyQT 中做同样的事情要快得多。

但我觉得我遗漏了一些东西,我本以为可以更容易地以一种很好的方式布置一堆重复格式的数字。

有些方框还需要一些图形内容,其中包含条形图和图表,但我可以使用 plotly 或 cairo。

虽然您最好使用 HTML 和 CSS 来执行此操作,如上文所述,但使用 Python 并不难,并且可以实现仅使用 tkinter。请在下面查看我的代码,以了解其工作原理的示例:

from tkinter import *

root = Tk()
frame1 = []
frame2 = []
c = 0
numberofboxes = 8 #change this to increase the number of boxes

for i in range(numberofboxes):
    if i % 4 == 0: #checks if the current box is the fourth in row
        c = c + 1 #if the current box is the forth in the row then this runs and increases a counter which we later use to determine the row
    if len(frame1) != c: #checks if the number of rows currently existing matches the number there should be
        frame1.append(Frame(root)) #if the numbers don't match this runs and creates a new frame which acts as another row
        frame1[c-1].pack(expand="True", fill="both") #packs the new row
    frame2.append(Frame(frame1[c-1], bg="green")) #this is where the boxes are created
    frame2[i].pack(ipadx="50", ipady="50", side="left", padx="10", pady="10", expand="True", fill="both") #this is where the boxes are placed on the screen

for i in range(len(frame2)): #this for loop places the items inside each box, all of this can be replaced with whatever is needed
    Label(frame2[i], text="CO"+str(i), bg="green", fg="white").pack(side="top", anchor="w")
    Label(frame2[i], text="12165.1"+str(i), bg="green", fg="white").pack(side="top", anchor="w")
    Label(frame2[i], text="+60.7"+str(i), bg="green", fg="white").pack(side="bottom", anchor="e")
    Label(frame2[i], text="+1.2"+str(i)+"%", bg="green", fg="white").pack(side="bottom", anchor="e")

root.mainloop()

所以本质上,我们为每一行创建一个 frame,每个框都是一个 frame,其中包含元素并安装在每一行的 "row frame" 4 中。

您应该仔细查看此脚本中 .pack() 的所有选项,以及实现所需布局和结果所必需的选项。

对于您的三角形,您很可能需要导入图像或在正确定位的 canvas 内绘制它们,或者(正如下面 Bryan Oakley 所指出的那样)您可以为箭头使用 unicode 字符,这会简单得多。