0

初次使用者。我是乔治梅森的一名研究生,我得到了很大的帮助,这里的社区给我留下了深刻的印象,所以我想我会提出一个问题。

我正在尝试使用 tkinter 绘制从文本文件中指定的点(这些点在代码顶部指定,但我将它们放在文本文件中)。我的任务要求我预测这些点,但我想更进一步,让它们直接从我的变量中读取,所以如果 .txt 发生变化,它们也会发生变化。我的问题是我不确定如何解析变量以便 tkinter 可以看到它们。

Here is the code:

"""
Read the following data (I put them into .txt first):
Polyline;
1: 1603714.835939442,142625.48838266544; 1603749.4678153452,142620.21243656706; 1603780.3769339535,142607.37201781105; 1603801.475846678,142582.27024446055; 1603830.4767344964,142536.14692804776;
2: 1602514.2066492266,142330.66992144473; 1602521.4127475217,142414.92978276964; 1602520.1146955898,142433.93817959353; 1602501.3840010355,142439.12358761206; 1602371.6780588734,142417.84858870413; 1602351.6610373354,142408.02716448065; 1602334.5180692307,142388.58748627454; 1602331.6999511716,142376.66073128115; 1602334.8067251327,142348.965322732; 1602338.308919772,142323.6111663878; 1602349.0226452332,142314.50124930218; 1602363.9090971674,142310.79584660195; 1602514.2066492266,142330.66992144473;

The following code define a function 'readPolylineFile' to read out data one line by one line
The readPolylineFile function will return two polylines

In addtion, try....except...finally are used to catch the exceptions
"""
import math
class Points:
    def __init__(self, x=0.0, y=0.0):
        self.x,self.y = x, y
class Polyline:
    def __init__(self, points =[] ):
        self.points = points
    def getLength(self):
        i = 0
        length =  0.0
        while i < len(self.points)-1:
            length += math.sqrt((self.points[i+1].x -self.points[i].x)**2 + (self.points[i+1].y -self.points[i].y)**2 )
            i += 1
        return length

## function to read out data one line by one line
## return polylines list
def readPolylineFile(fileName):
    ## Declare variables that will be used outside of try blocks
    polylines = []  ## empty polyline list to keep all polylines
    f = None # empty file object
    try:    
        f = open(fileName, 'r')  ## Open the file and assign the return object to f      
        firstPolyLineNum = 0
        index = 0
        for line in f:
            index += 1
            if index == 1: ## Pass the first line
                continue       
            coords = line.split(':')[1]            
            eachcoords = coords.split(';')          
            coordsLen = len(eachcoords)
            points = [] ## Declare a points list to keep the points for each polyline
            for i in range(coordsLen-1):
                singlecoords = eachcoords[i]
                xCoord = singlecoords.split(',')[0]
                yCoord = singlecoords.split(',')[1]
                print singlecoords
                try:
                    point = Points(float(xCoord),float(yCoord))
                    points.append(point)

                except ValueError:
                   print 'Can not convert non-number to float'
                except TypeError:
                   print 'Object type can not conver to float' 
            ## Create a polyline object based on the points
            polyline = Polyline(points)
            polylines.append(polyline)

    except IOError: ##File does not exist
        print 'IO Error while opening or reading the file'
    finally:
        if f:  ## If file object exist, close the file
            print 'Input .txt has been read and is now closed......'
            f.close()

    return polylines  ## Return the polylines


polylines = readPolylineFile('F://GMU Fall 2013/GGS 650/HW6/input.txt')

try: 
    ## Get the first polyline
    polyLine1 = polylines[0]
    lengthForFirstPoly = polyLine1.getLength()
    print "length for first polyline (first 5 coordinates) -> ", lengthForFirstPoly

    ## Gets the points for second polyline
    polyLine2 = polylines[1]
    lengthForSecondPoly = polyLine2.getLength()
    print "length for Second polyline (last 13 coordinates) -> ", lengthForSecondPoly

except:
    print "error in processing polyline objects created"

from Tkinter import *

master = Tk()
master2 = Tk()

w = Canvas(master, width=800, height=600)
w.pack()
w.create_line(0, 0, 200, 100)

w = Canvas(master2, width=800, height=600)
w.pack()
w.create_line(0, 0, 200, 297)
mainloop()
4

1 回答 1

0

您需要做的就是在折线中创建一个方法,该方法将所有点的坐标作为平面列表返回,然后使用它来创建您的线。

这是一个返回扁平坐标列表的快速而肮脏的示例:

class Polyline(self):
    ...
    def getCoordinates(self):
        coords = []
        for point in self.points:
            coords.append(point.x)
            coords.append(point.y)
        return coords

以下是如何在画布上为每条折线创建一条线:

for polyline in polylines:
    canvas.create_line(polyline.getCoordinates())
于 2013-10-06T12:08:12.237 回答