[Tutor] lists and Entry

Andre Engels andreengels at gmail.com
Wed Jan 14 12:39:54 CET 2009


On Wed, Jan 14, 2009 at 11:52 AM, Mr Gerard Kelly
<s4027340 at student.uq.edu.au> wrote:
> There is a little Tkinter program. It lets you type something in a box,
> and will display it at the command line.
>
>
> from Tkinter import *
>
> master = Tk()
>
> e = Entry(master)
> e.pack()
>
> e.focus_set()
>
> def callback():
>  s=e.get()
>  print s
>
> b = Button(master, text="get", width=10, command=callback)
> b.pack()
>
> mainloop()
>
>
>
> The get() method returns a string, how do I make it return a list?
> I want to be able to type in 1,2,3 into the box and get [1,2,3] to
> appear on the command line.
>
> If I change the callback() method so that it says
> s=[e.get()]
> I just get a list with one element, the string: ['1,2,3']
>
> If I make it
> s=list(e.get())
> I get a list with every character as an element: ['1', ',', '2', ',', '3']
>
> How to just get plain [1,2,3]?

You'll have to work with the string. Assuming that the string will
always be a couple of integers, separated by commas (if getting input
from the keyboard, create a loop so that data are being called again
and again until it parses correctly), you can get what you want with:

s=[int(n) for n in e.get().split(',')]

Explaining this Python:

e.get(), as you have noticed, is a string consisting of whatever has
been put in, in this case '1,2,3'.

e.get.split(',') means "split e.get() into pieces at each comma, and
make a list out of it'. This gives: ['1','2','3'].

And finally

[int(n) for n in A] with A being a list (or more generally, anything
enumerable) gives a list consisting of the int value of the items in
A.




-- 
André Engels, andreengels at gmail.com


More information about the Tutor mailing list