pythonclasstkinterinit

TypeError in __init__(), unexpected argument python


I have the following code:

from tkinter import *

class Button:   
    def __init__(self, master):
        frame = Frame( master )
        frame.pack()

        self.printButton = Button(frame, text = "Print Message", command=self.printMessage)
        self.printButton.pack(side = LEFT)

        self.quitButton = Button(frame, text = "Quit", command = frame.quit)
        self.quitButton.pack(side = LEFT)

    def printMessage(self):
        print(" WORKING!! " )       



root = Tk()
b = Button(root)
root.mainloop()

Which does not seem to be wrong in anyway... But when I run it, terminal says:

Traceback (most recent call last):
File "class.py", line 23, in <module>
b = Button(root)
File "class.py", line 10, in __init__
self.printButton = Button(frame, text = "Print Message", command=self.printMessage)
TypeError: __init__() got an unexpected keyword argument 'command'

I wrote all these codes according to a tkinter tutorial. And in the tutorial, the code works well. Any help would be appreciated. Thanks in advance!


Solution

  • Tkinter already has a Buttonclass and when you create your class you now have overwritten the tkinter class named Button. So, when you try to create a tkinter button like this:

    self.printButton = Button(frame, text = "Print Message", command=self.printMessage)
    

    You are now referencing your button because you overwrote the tkinter button previously. And since your button only takes one argument and you give it three, It will throw you an error. The way to fix this would be to change your import line to this:

    import tkinter as tk
    

    And then reference any tkinter functions with tk.*. For example:

    root = Tk()
    

    would become:

    root = tk.Tk()
    

    Then your button would be referenced by Button while the tkinter button would be referenced by tk.Button. This way you could easily distingush between the two. However you could also just call your button something like myButton which would also fix the problem.