在tkinter中读取文件并写入行的Python函数

时间:2018-07-27 11:15:43

标签: python canvas tkinter

我必须使函数draw(file_name)能够读取带有数字的文件:

100 50
150 100
50 100
100 150

类似这样。一行是一个坐标x,y

然后以更细的线条画线:第一线=第一点至第二线=第二点,第二线=第二点至3线= 3点

import tkinter

canvas = tkinter.Canvas()
canvas.pack()
def draw(file):
    file=open(file,"r")
    line=file.readline()
    i=line.find(" ")
    x, y = int(line[:i]), int(line[i:])
    while line != "":
        line = file.readline()
        i = line.find(" ")
        x2, y2 = int(line[:i]), int(line[i:])
        canvas.create_rectangle(x, y, x2, y2)
        x,y=x2,y2            
    file.close()

draw("file.txt")
canvas.mainloop()

这是我的代码,但是不起作用

3 个答案:

答案 0 :(得分:1)

您可以尝试以下一种方法:

import tkinter

canvas = tkinter.Canvas()
canvas.pack()

def draw(filename):
    points = []
    with open(filename, "r") as infile:
        for line in infile:
            line = line.split()
            x, y = (int(line[0]), int(line[1]))
            points.append((x,y))

    for i in range(0,len(points)-1):
        canvas.create_line(points[i][0], points[i][1], points[i+1][0],points[i+1][1])

draw("points.txt")
canvas.mainloop()

您需要使用canvas.create_line(),因为它是您要绘制的线。

答案 1 :(得分:0)

这如何为您工作? 我正在使用line.split('')来从文件中获取x和y坐标

import tkinter

canvas = tkinter.Canvas()
canvas.pack()

def draw(file):
    x = None
    y = None
    with open(file,"r") as file:
        for line in file:
            print(line)
            if x is None:
                x, y = line.strip().split(' ')
            else:
                x2, y2 = line.strip().split(' ')
                canvas.create_line(x, y, x2, y2)
                x = x2
                y = y2         

draw("file.txt")
canvas.mainloop()

如果这行不通,您能解释一下为什么发生什么以及您期望发生什么。

答案 2 :(得分:-1)

def draw(file): with open(file,"r") as f: x, y = int(line[:i]), int(line[i:])
for line in f: i = line.find(" ") x2, y2 = int(line[:i]), int(line[i:]) canvas.create_rectangle(x, y, x2, y2) x,y=x2,y2
file.close()