Get text from matplotlib's TextBox and save to a file

Viewed 85

How can I get the text from a matplotlib's TextBox? I have this:

(...)
ax_info = plt.axes([0.7, 0.7, 0.2, 0.25])
info_box = TextBox(ax_info, label='', initial='INFO:')

and then, when a button is pressed I have the following function:

def get_info(text):
    info = text
    np.savetxt(os.path.join(directory, 'info.txt'), info)


info_box.on_submit(get_info)

Why doesn't this work?

1 Answers

The problem doesn't seem to be getting the text from the text box, but rather the step where you save the text to a file.

np.savetxt expects an array-like object to save to a file, and also by default expects the values to be as floats (you can change this if necessary).

To keep using np.savetxt, you must first make your string "array-like", and then we need to specify that the format is a string, not a float, for example:

def get_info(text):
    # make info a list, so it is array-like
    info = [text]
    
    # specify format as a string
    np.savetxt(os.path.join(directory, 'info.txt'), info, fmt="%s")

If you are just writing one line to a text file, however, you could probably just use the built-in python IO functionality, rather than numpy. Something like:

def get_info(text):
    info = text
    
    with open(os.path.join(directory, 'info.txt'), 'w') as f:
        f.write(info + '\n')
Related