话不多说,直接上代码:
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QVBoxLayout
import sys
import math
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(500, 250)
self.setWindowTitle("坐标系")
self.lb = QLabel("点1到原点距离:", self)
self.lb.move(20, 40)
self.lb2 = QLabel("点1与原点的角度:", self)
self.lb2.move(20, 80)
self.lb3 = QLabel("点2到原点距离:", self)
self.lb3.move(20, 120)
self.lb4 = QLabel("点2与原点的角度:", self)
self.lb4.move(20, 160)
self.bt1 = QPushButton('查询', self)
self.bt1.move(20, 200)
self.edit = QLineEdit('', self)
self.edit.move(150, 40)
self.edit2 = QLineEdit('', self)
self.edit2.move(150, 80)
self.edit3 = QLineEdit('', self)
self.edit3.move(150, 120)
self.edit4 = QLineEdit('', self)
self.edit4.move(150, 160)
self.bt1.clicked.connect(self.calc_angle)
self.show()
def calc_angle(self):
x1 = float(self.edit.text()) * math.cos(math.radians(int(self.edit2.text())))
y1 = float(self.edit.text()) * math.sin(math.radians(int(self.edit2.text())))
x2 = float(self.edit3.text()) * math.cos(math.radians(int(self.edit4.text())))
y2 = float(self.edit3.text()) * math.sin(math.radians(int(self.edit4.text())))
angle = 0
dy = y2 - y1
dx = x2 - x1
if dx == 0 and dy > 0:
angle = 90
print('顺时针:', angle, '°')
if dx == 0 and dy < 0:
angle = 270
print('顺时针:', angle, '°')
if dy == 0 and dx > 0:
angle = 0
print('顺时针:', angle, '°')
if dy == 0 and dx < 0:
angle = 180
print('顺时针:', angle, '°')
if dx > 0 and dy > 0:
angle = math.atan(dy / dx)* 180 / math.pi
print('东偏北:',angle,'°')
elif dx < 0 and dy > 0:
angle = 90 - math.atan(dy / abs(dx))* 180 / math.pi
print('北偏西:', angle, '°')
elif dx < 0 and dy < 0:
angle = math.atan(dy / dx)* 180 / math.pi
print('西偏南:', angle, '°')
elif dx > 0 and dy < 0:
angle = math.atan(abs(dy) / dx)* 180 / math.pi
print('东偏南:', angle, '°')
length = math.sqrt(dy * dy + dx * dx)
print(length)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
最后的结果之所以有那么多小数点,是因为math.pi,其实就是π,3.1415926…,有很多小数位!
其实上文就是,在一个坐标系中,已知两个点到坐标原点的距离,以及它们和横轴的角度(这都是需要自己手动输入的),那么就以第一个点为此时的坐标原点,求第二个点到第一个点的距离,以及第二点在第一点的相关方位。
ps: 我这里是已知两点到原点的距离和角度,就像在一个极坐标里一样,如果直接知道两点的横纵坐标,那么会更好求。