首页 > 解决方案 > 尝试打印变量时出现语法错误

问题描述

我对 python 很陌生(一般编码)。如果相关,我使用 Spyder 4.2.1(Python 3.7.9 64 位 | Qt 5.12.10 | PyQt5 5.12.3 | Windows 10)。

如果我用鼠标单击绘制的图表,我试图弄清楚如何存储坐标。谷歌搜索一些问题得到了很好的例子,我想在他们的问题和答案中尝试提供的代码。我尝试使用以下代码的问题:get Coordinates of matplotlib plot figure python with mouse click

但是,如果我尝试运行下面的代码(对于最初的提问者来说,这似乎工作正常),我得到一个 SyntaxError: invalid syntax,它指向 ' y = %d 之后

可悲的是,我在这里不知所措。

import numpy as np
import matplotlib.pyplot as plt


x = np.arange(-10,10)
y = x**2

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y)

coords = []

def onclick(event):
    global ix, iy
    ix, iy = event.xdata, event.ydata
    print 'x = %d, y = %d' %(
        ix, iy)

    global coords
    coords.append((ix, iy))

    if len(coords) == 2:
        fig.canvas.mpl_disconnect(cid)

    return coords
cid = fig.canvas.mpl_connect('button_press_event', onclick)

在此处输入图像描述

标签: pythonnumpymatplotlib

解决方案


您需要将打印语句放在括号中。IE:

print ("x = %d, y = %d" %(
        ix, iy))

推荐阅读