Gui画布条形图不显示list NUMBE

2024-06-28 11:38:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个GUI代码,可以根据数据生成图形。在代码中,它显示数据,然后显示一些数字,并根据这些数字更改条形图的高度。代码将所有数据放在图形中条形图的上方

#Read text file and turn it into a nested list
def readfile():
    textlist = [line.split(',') for line in open("chookfood.txt", 'r')]
    return textlist

#makes 'l' a value to pull data from the text sheet. 
l = readfile()
print(l[0][1], l[0][2], l[1][1], l[1][2], l[3][1], l[3][2], l[4][1], l[4][2])


我收到一条错误消息:

Traceback (most recent call last):
   y0 = c_height - (y * y_stretch + y_gap)
TypeError: can only concatenate str (not "int") to str

代码的其余部分:


import tkinter as tk


#Read text file and turn it into a nested list
def readfile():
    textlist = [line.split(',') for line in open("chookfood.txt", 'r')]
    return textlist

#makes 'l' a value to pull data from the text sheet. 
l = readfile()
data = (l[0][1], l[0][2], l[1][1], l[1][2], l[3][1], l[3][2], l[4][1], l[4][2])


root = tk.Tk()
root.title("Bar Graph")


c_width = 400  # Window's width
c_height = 350  # Window's height
c = tk.Canvas(root, width=c_width, height=c_height, bg='white')#White store
c.pack()

# Bar Graphing Scale
y_stretch = 1  # The highest y = max_data_value * y_stretch
y_gap = 25  # The gap between lower canvas edge and x axis
x_stretch = 16  # 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="blue")

    # Put the y value above the bar
    c.create_text(x0 - 1, y0, anchor=tk.SW, text=str(y))

root.mainloop()


data = (1,2,3,4,5)它是罚款,但不是与其他人。我怎样才能解决这个问题


Tags: andtheto代码textfordatavalue
1条回答
网友
1楼 · 发布于 2024-06-28 11:38:11

数据在我看来就像一个字符串列表,这意味着y是一个字符串。文件读取方法返回字符串,您永远不会将其转换为int()。我建议换衣服

print(l[0][1], ...

print(repr(l[0][1], ...

而是为了显示问题,并改变

y0 = c_height - (y * y_stretch + y_gap)

y0 = c_height - (int(y) * y_stretch + y_gap)

(这会将y转换为int,因此如果要支持小数,请小心。)

相关问题 更多 >