Python 如何使用两点的 x 和 y 坐标绘制一条线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33240374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:04:47  来源:igfitidea点击:

How can draw a line using the x and y coordinates of two points?

pythonpython-3.x

提问by RezaOptic

I would like to know how to draw a line using the x and y coordinates of two 2-dimensional points. I tried the turtle graphics, but it works using degrees.

我想知道如何使用两个二维点的 x 和 y 坐标绘制一条线。我尝试了海龟图形,但它使用度数工作。

采纳答案by Nick

You could make use of pygame depending on what you are doing it for as it allows a similar:

您可以根据您的用途使用 pygame,因为它允许类似的:

line(Surface, color, (x1,y1), (x2,y2), width)

For Example, when the environment has been set up:

例如,当环境已经设置好时:

pygame.draw.line(screen, (255,0,255), (20,20), (70,80), 2)

can draw:

可以画:

Test line

测试线

回答by Rob S.

You could calculate the angle from the 4 points using the following formula

您可以使用以下公式从 4 个点计算角度

angle = arctan((y2-y1)/(x2-x1))

Just a warning, depending on the math library you use, this will probably output in radians. However you can convert radians to degrees using the following formula.

只是一个警告,根据您使用的数学库,这可能会以弧度输出。但是,您可以使用以下公式将弧度转换为度数。

deg = rad * (180/pi)

回答by efirvida

Depending of your needs for plotting you can use matplotlib

根据您的绘图需要,您可以使用matplotlib

import matplotlib.pyplot as plt
plt.plot([x1,x2],[y1,y2])
plt.show()

回答by volent

If you are already using turtleyou can use a Tkintercanva :

如果您已经在使用turtle,则可以使用Tkinter画布:

import Tkinter
x1, y1, x2, y2 = 10, 20, 30, 40
window = Tkinter.Tk()
canva = Tkinter.Canvas(window)
line = canva.create_line(x1, y1, x2, y2)
canva.pack()

回答by cdlane

I tried the turtle graphics, but it works using degrees.

我尝试了海龟图形,但它使用度数工作。

Your premise doesn't hold -- turtle can do it, no degrees needed:

你的前提不成立——乌龟可以做到,不需要学位:

import turtle

point1 = (50, 100)
point2 = (150, 200)

turtle.penup()
turtle.goto(point1)
turtle.pendown()
turtle.goto(point2)

turtle.hideturtle()
turtle.exitonclick()

回答by Steschu

Just for completeness, you can also use the ImageDraw module of Pillow(Python Image Library / PIL fork). That way you don't need a window and you can save the drawn image into a file instead.

为了完整起见,您还可以使用PillowImageDraw 模块(Python Image Library / PIL fork)。这样您就不需要窗口,而是可以将绘制的图像保存到文件中。

from PIL import Image, ImageDraw

im = Image.new('RGB', (100, 100))

draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)

im.save('test.png')