user1104854
user1104854

Reputation: 2167

Trouble with Tkinter entry widget

I'm following this intro to tkinter, specifically the dialog entry example on page 29. http://www.ittc.ku.edu/~niehaus/classes/448-s04/448-standard/tkinter-intro.pdf

I'm getting the following error:

d = MyDialog(root)
TypeError: this constructor takes no arguments

I deleted the argument from the variable d, and the argument for wait_window (see the code below) and the program will run, however there is no entry field.

Here is the code

from Tkinter import *

class MyDialog:

    def init(self, parent):

        top = Toplevel(parent)

        Label(top, text="Value").pack()

        self.e = Entry(top)
        self.e.pack(padx=5)

        b = Button(top, text="OK", command=self.ok)
        b.pack(pady=5)

    def ok(self):
        print "value is", self.e.get()

        self.top.destroy()

root = Tk()
Button(root, text="Hello!").pack()
root.update()

d = MyDialog(root)

root.wait_window(d.top)

Upvotes: 1

Views: 333

Answers (2)

mgilson
mgilson

Reputation: 310187

You need to change

def init(self, parent):
    ... 

to

def __init__(self, parent):
    ...

(Note the bracketing double underscores).

In python, the documentation is a little fuzzy on what it calls the constructor, but __init__ is often refered to as the constructor (although some will argue that is the job of __new__.). Semantics aside, the arguments passed to MyClass(arg1,arg2,...) will get passed to __init__ (provided you don't do funny things in __new__ which is a discussion for a different time). e.g.:

class MyFoo(object): #Inherit from object.  It's a good idea
    def __init__(self,foo,bar):
       self.foo = foo
       self.bar = bar

my_instance = MyFoo("foo","bar")

As your code is, since you don't define __init__, the default is being used which is equivalent to:

def __init__(self): pass

which takes no arguments (other than the compulsory self)


You'll also need to do:

self.top = Toplevel(...)

since later you try to get the top attribute (d.top), but d has no attribute top since you never added as an attribute.

Upvotes: 3

user647772
user647772

Reputation:

Change

def init(self, parent):

to

def __init__(self, parent):

See the documentation of object.__init__.

Upvotes: 3

Related Questions