is there a way to read in comma separated numbers using the tk entry widget?
For example, suppose a user entered the following in an entry widget:
4, 5, 8.2, 2,3.9
The reason is that I would like to convert the entered numbers into a list / array.
I currently have my entry widget set up as:
self.zeros1 = tk.Entry(group_1)
self.zeros1.grid(row = 0, column = 1, sticky = tk.W)
Just read the contents of the Entry widget, split it on commas, and convert the resulting list of strings to numbers.
There is not built-in support for this AFAIK, but you can access the data as a string as you would normally (I think that’s either the
get method of the widget, or the
get method of a
StringVar associated with it), and then parse it as if you had gotten that string in any other way.
There are things like
IntVar etc. that interpret their contents as an integer etc. instead of a string, but arbitrary custom formats (such as this one) can’t be predicted ahead of time.
thank you both for your responses. Yes, that is in line with what I am researching now:
************************ Update ******************************
Found a solution for those in a similar bind:
temp = self.zeros1.get()
numbers = [float(s) for s in re.findall(r'-?\d+\.?\d*', temp)]
For this to work, instead of entering the numbers via comma separation
as in: 4.5, 5, 3.2
Enter the numbers by separating them via a space, as in:
4.5 5 3.2
The code with
re that you show would also work if the input has those commas in it. However, it’s not as robust as using a tool such as the
split method of the string in order to get the individual values. For example,
1.2e3 is a legal way to write a floating-point number in Python (meaning the same as
1200.0), but the regex code will understand it as two separate values
3.0. (Do you see why?)
Yes, you’re right, it does accept comma separated numbers as well. I must have inadvertently mistyped when testing the code last night and gotten an error (maybe, two commas or two periods), it was very late last night when I was testing the code. I will look into the split method that you mentioned. However, my application I don’t think will be needing scientific inputs. I am using my code for transfer function entries, i.e., zeros and poles via GUI entries. For example:
TF1: [2.1, 4.3] / [1.3, 1.1]
TF2: [3, 5.2] / [10.5, 1, 4.5]
I put these two entries in series and plot their gain and phase margin via the two modules:
import matplotlib.pyplot as plt
In any case, I appreciate your feedback.