Python:使用来自 SQlite3 数据库的数据在 Tkinter 中构建条形图

Python: Building a Bar Chart in Tkinter with Data From an SQlite3 Database

在我开始之前,我是堆栈溢出的新手,所以如果我的问题格式不正确,我深表歉意。这也是我学校图书馆的 A-level 学校项目,旨在帮助图书馆的管理。我创建了一个 table,其中包含名为 'pastLoans'(see here ), I need a way of finding out which books are most popular among library users and represent the findings on a bar chart. To do this I created an SQL command that counts the number of times a book title appears from the 'book' column of the 'pastLoans' table, currently I have 2 books in there (see here) 的有关学生先前贷款的数据。

由于Tk.canvas条形图的性质,除了整数分别作为数据外,所以我需要找到一种方法来拆分书名和它在[=中出现的次数27=],使用它发生的次数作为条形图上显示的数据,书名作为X轴上的标签。

目前我已经编写了 SQL 命令,使用 SQLite3 中的 'COUNT' 函数从 table 中提取我需要的数据,其中包含有关过去贷款的数据,此外,我还为条形图编写了框架代码,并测试了它是否适用于列表中的示例数据,例如 [1,2,3,4,5,..]

请注意条形图在 Tkinter 上成功显示了正确的数据值,遗憾的是我无法添加结果图片,因为我没有足够的代表。

我的代码如下所示:

    command = ("SELECT book,COUNT(book) AS cnt FROM pastLoans GROUP BY 
    book ORDER BY cnt DESC;")

    c.execute(command)
    result = c.fetchall()
    print (result)                            
    """This is the code for pulling the book name and amount of books 
    from the "pastLoans" as well as the book name, the result is this:

    >>> [('Book', 1), ('Harry Potter', 1)]


    This is my bar chart frame:"""

    data = [1, 2, 3, 4, 5] #The data used here is sample data.

    g_width = 900  # Define it's width
    g_height = 400  # Define it's height
    g = tk.Canvas(self, width=g_width, height=g_height)
    g.grid()

    # The variables below size the bar graph
    y_stretch = 15  # The highest y = max_data_value * y_stretch
    y_gap = 20  # The gap between lower canvas edge and x axis
    x_stretch = 10  # Stretch x wide enough to fit the variables
    x_width = 20  # The width of the x-axis
    x_gap = 20  # The gap between left canvas edge and y axis

    for x, y in enumerate(data):

        # coordinates of each bar

        # Bottom left coordinate
        x0 = x * x_stretch + x * x_width + x_gap

        # Top left coordinates
        y0 = g_height - (y * y_stretch + y_gap)

        # Bottom right coordinates
        x1 = x * x_stretch + x * x_width + x_width + x_gap

        # Top right coordinates
        y1 = g_height - y_gap

        # Draw the bar
        g.create_rectangle(x0, y0, x1, y1, fill="red")

        # Put the y value above the bar
        g.create_text(x0 + 2, y0, anchor=tk.SW, text=str(y))

因为您已经完成了让 tkinter 显示条形图和上面的一些文本的所有工作,所以您只需要迭代 result 而不是 data:

# Sort so that the most popular book is on the left
result.sort(key=lambda e: e[1], reverse=True)

for x, (name, y) in enumerate(result):
   ...

   # Put the name above the bar
   g.create_text(x0 + 2, y0, anchor=tk.SW, text=name)

您可能需要改变 x_stretch 变量,以使文本不重叠。