我正在试图找出最简单的方法来制作上面的蝙蝠图。我正在学习popupWindow.setOutsideTouchable(false);
,我知道我可以使用popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(true);
,tkinter
和Canvas
来完成这项工作,但它似乎有太多的冗余。
答案 0 :(得分:2)
一些谷歌搜索显示this链接到我。
我已经包含了那里给出的示例代码,我希望对它进行足够的评论,以便您了解正在发生的事情。
我稍微不确定我的for循环描述的准确性,所以如果有任何问题请评论。
import tkinter as tk
# Define the data points
data = [20, 15, 10, 7, 5, 4, 3, 2, 1, 1, 0]
root = tk.Tk()
root.title("Bar Graph")
c_width = 400 # Define it's width
c_height = 350 # Define it's height
c = tk.Canvas(root, width=c_width, height=c_height, bg='white')
c.pack()
# 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
# A quick for loop to calculate the rectangle
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 = c_height - (y * y_stretch + y_gap)
# Bottom right coordinates
x1 = x * x_stretch + x * x_width + x_width + x_gap
# Top right coordinates
y1 = c_height - y_gap
# Draw the bar
c.create_rectangle(x0, y0, x1, y1, fill="red")
# Put the y value above the bar
c.create_text(x0 + 2, y0, anchor=tk.SW, text=str(y))
root.mainloop()
答案 1 :(得分:1)
最后我写了一些简单的代码,这可能有点多余而且不够灵活。
from tkinter import *
root = Tk()
root.title("Bar Graph")
c_width = 500
c_height = 200
c = Canvas(root, width=c_width, height=c_height)
c.pack()
c.create_rectangle(20, 140, 120, 180, fill="red")
c.create_text(70, 130, text="Projects--20%")
c.create_rectangle(140, 160, 240, 180, fill="blue")
c.create_text(190, 150, text="Quizzes--10%")
c.create_rectangle(260, 120, 360, 180, fill="green")
c.create_text(310, 110, text="Midterm--30%")
c.create_rectangle(380, 100, 480, 180, fill="orange")
c.create_text(430, 90, text="Final--40%")
c.create_line(0, 180, 500, 180)
root.mainloop()