Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

python - I get a Syntax Error trying to print variables

I am quite new to python (to coding in general). I use Spyder 4.2.1 (Python 3.7.9 64-bit | Qt 5.12.10 | PyQt5 5.12.3 | Windows 10), if that's relevant.

I am trying to figure out how to store coordinates if I click on a plotted diagram with a mouse. Googling for some of the questions resulted in good examples and I wanted to try the provided codes in their questions and answers. Question that I tried to use the code from: get Coordinates of matplotlib plot figure python with mouse click

However, if I try to run the code below (which seems to work fine up until that point for the original asking person), I get a SyntaxError: invalid syntax, and it points to the ' right after the y = %d

I am at a loss here sadly.

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)

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to put the print statement in brackets. i.e.:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...