Accepting Tkinter input

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • psychofish25
    New Member
    • Jul 2007
    • 60

    Accepting Tkinter input

    I am trying to make a simple random number generator GUI, and for some reason I get an error trying to take the text out txt1 and txt2. Why isn't this working? The error says AttributeError: 'NoneType' object has no attribute 'get'

    Code:
    from Tkinter import *
    import random
    class myform:
        def __init__(self,form):
            form.wm_title('Random')
            lbl1=Label(form,text='Low:').grid(row=0)
            self.txt1=Entry(form).grid(row=0,column=1)
            lbl2=Label(form,text='High:').grid(row=1)
            self.txt2=Entry(form).grid(row=1,column=1)
            btn1=Button(form,text='Submit',command=self.onClick).grid(row=2)
            self.lbl3=Entry(form).grid(row=2,column=1)
        def onClick(self):
            low=self.txt1.get()
            high=self.txt2.get()
            output=random.randrange(low,high)
            self.lbl3.config(text=output)
            self.lbl3.update_idletasks()
    root=Tk()
    myform(root)
    root.mainloop()
  • jlm699
    Contributor
    • Jul 2007
    • 314

    #2
    So there were two errors. The first (the one that you mentioned) was caused by the fact that you combined the initialization of Entry() with the grid command. By combining those calls into as ingle line, python took the "last" returned element and stored it to txt1 and txt2. This means instead of storing a Entry widget, it was storing the NoneType that is returned by the grid command. What you did is valid, it just doesn't give you what you want. If you wanted to still have them on a single line of code you would have to make use of the name parameter and then call the widget by name. That or make use of a text variable.

    The second error was you forgot to convert the return from the get() command to int... however I'm sure you would've realized that as soon as you solved the first error. Anyway, here's the fixed code:
    [code=python]from Tkinter import *
    import random

    class myform:
    def __init__(self,f orm):
    form.wm_title(' Random')
    lbl1=Label(form ,text='Low:').g rid(row=0)
    self.txt1=Entry (form)
    self.txt1.grid( row=0,column=1)
    lbl2=Label(form ,text='High:'). grid(row=1)
    self.txt2=Entry (form)
    self.txt2.grid( row=1,column=1)
    btn1=Button(for m,text='Submit' ,command=self.o nClick)
    btn1.grid(row=2 )
    self.lbl3=Entry (form)
    self.lbl3.grid( row=2,column=1)

    def onClick(self):
    low=int(self.tx t1.get())
    high=10
    high=int(self.t xt2.get())
    output=random.r andrange(low,hi gh)
    self.lbl3.delet e(0, END)
    self.lbl3.inser t(0, output)

    root=Tk()
    myform(root)
    root.mainloop()[/code]

    Comment

    • psychofish25
      New Member
      • Jul 2007
      • 60

      #3
      Oh okay excellent, thanks

      Comment

      Working...