[Tutor] Need help with Tkinter Entry()..

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 16 Apr 2001 09:31:33 -0700 (PDT)


On Mon, 16 Apr 2001, James Matthews wrote:

> 
> #######################################################
> from Tkinter import *
> 
> def do():
>     ENTRY = entry.get()
>     for times in range(0,13):
>         E = '%d X %d = %d' % (ENTRY,times,ENTRY*times)
>         label = Label(root,text=E)
>         label.pack()
> 
> root = Tk()
> entry = Entry(root)
> entry.pack()
> button = Button(root,text='Times',command=do)
> button.pack()
> ######################################################
> 
> I dont know how to get the entry to get the number or
> text it always say that it needs a integer. but
> when i call it in the python shell it says that it is
>      .274467 or something like that and this number is
> always different when i run the program

On the whole, your program looks ok.  There are a few nitpicky things
we'll need to fix to get things working:


1.  The Entry doesn't have an initial value --- it starts off empty by
default --- so let's check within your do() to see if the entry has a good
value in there.  There are a few ways to do this (some with exception
handling), but for now, let's just check that the user's not putting in an
empty string.


2.  Also, the value that you get out of entry.get() is a string, so you'll
want to coerce it into an integer form, because arithmetic on strings
doesn't work.  For example:

###
>>> "3" + "4"           ## "Addition" between two strings is concatenation
'34'
>>> "3" * "4"
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: can't multiply sequence with non-int
>>> int("3") * int("4")                ## Converting strings to ints first
12                         
###


3.  Don't forget to do a mainloop() at the end of your program, to tell
Python that the gui's constructed and we're ready to listen to the user.  
The reason this is necessary is because, if we get to the bottom of the
program, Python assumes that we're done with everything, and quits too
prematurely.



Here's a version of the code with the corrections:

###
from Tkinter import *

def do():
    ENTRY = entry.get().strip()
    if ENTRY == "": return       ## Do nothing if we don't have a string
    NUMENTRY = int(ENTRY)
    for times in range(0,13):
        E = '%d X %d = %d' % (NUMENTRY, times, NUMENTRY*times)
        label = Label(root,text=E)
        label.pack()

root = Tk()
entry = Entry(root)
entry.pack()
button = Button(root, text='Times', command=do)
button.pack()

mainloop()
###


Hope this helps!