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

Python:使用SQlite3数据库中的数据在Tkinter中构建条形图,python,tkinter,sqlite,tkinter-canvas,python-3.6,Python,Tkinter,Sqlite,Tkinter Canvas,Python 3.6,在我开始之前,我还不熟悉堆栈溢出,所以如果我的问题格式不好,我很抱歉。这也是我学校图书馆的A级学校项目,旨在帮助管理图书馆。我已经创建了一个表,其中包含有关学生以前贷款的数据,名为“pastLoans”(),我需要一种方法来找出哪些书籍在图书馆用户中最受欢迎,并将结果显示在条形图上。为此,我创建了一个SQL命令,用于计算图书标题从“pastLoans”表的“book”列中出现的次数,目前我在其中有两本书() 由于Tk.canvas条形图的性质,除了分别作为数据的整数之外,只有整数,因此我需要找到

在我开始之前,我还不熟悉堆栈溢出,所以如果我的问题格式不好,我很抱歉。这也是我学校图书馆的A级学校项目,旨在帮助管理图书馆。我已经创建了一个表,其中包含有关学生以前贷款的数据,名为“pastLoans”(),我需要一种方法来找出哪些书籍在图书馆用户中最受欢迎,并将结果显示在条形图上。为此,我创建了一个SQL命令,用于计算图书标题从“pastLoans”表的“book”列中出现的次数,目前我在其中有两本书()

由于Tk.canvas条形图的性质,除了分别作为数据的整数之外,只有整数,因此我需要找到一种方法来拆分图书的名称和它在表中出现的次数,使用它出现的次数作为条形图上显示的数据,使用图书的名称作为X轴上的标签

目前,我使用SQLite3中的“COUNT”函数对SQL命令进行了编码,以从包含过去贷款数据的表中提取所需数据,此外,我还对条形图的框架进行了编码,并使用列表中的示例数据对其进行了测试,例如[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显示条形图和上面的一些文本的所有工作,因此您只需迭代
结果
,而不是
数据

# 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\u stretch
变量,以便文本不会重叠。

我不太明白您的问题。似乎您希望添加书籍的标题而不是
str(y)
,但您不知道如何在结果中迭代条目。我希望能够将书籍的名称(字符串)和书籍出现的次数(整数)分开并绘制书的名称和X轴,以及书在Y轴上出现的次数。