在开始之前,我是新的堆栈溢出,所以如果我的问题格式不正确,我会道歉。这也是我学校图书馆的A级学校项目,旨在帮助管理图书馆。我创建了一个表格,其中包含有关学生之前贷款的数据,这些贷款名为“pastLoans'(see here )”,我需要一种方法来查找图书馆用户中最受欢迎的图书,并在条形图上显示结果图表。为此,我创建了一个SQL命令,用于计算书名从“书”中出现的次数。 “过去的漫画”一栏'表,目前我有2本书(see here)。
由于Tk.canvas条形图的性质只是分别作为数据的整数,所以我需要找到一种方法来分割书的名称和它在表中出现的次数,使用的数量它作为要显示在条形图上的数据发生的时间,以及作为X轴上的标签的书名。
目前,我已经编写了SQL命令,用于从包含有关过去贷款数据的表中提取我需要的数据,使用' COUNT' SQLite3中的函数,另外我已经为条形图编码了框架并测试了它与列表中的样本数据一起工作,例如[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))
答案 0 :(得分:0)
由于您已经完成了让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
变量,以使文本不重叠。