Synthesis
Synthesis

Reputation: 21

Python Tkinter Class Object Has No Attribute 'mainloop'

I'm trying to write a basic program to create and manage tasks. I have run into an error that I've researched but can't find a solution to it that makes sense. I use root = tk.Tk() and pass that to a class. However when I call that class with the mainloop() method, I get this error and I don't know why I'm getting it:

AttributeError: 'MainApplication' object has no attribute 'mainloop'

Below is my code for reference:

 import tkinter as tk


class MainApplication:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.entry = tk.Entry(self.frame)
        self.entryButton = tk.Button(self.frame, text="Enter", command = 'create_entry')
        self.titlelabel = tk.Label(self.frame, text="Enter a task and manage the list")
        self.entry.grid(row=1, column=0)
        self.entryButton.grid(row=1, column=1)
        self.titlelabel.grid(row=0, column=0, columnspan=2)
        self.configure_gui()

    def configure_gui(self):
        self.master.geometry("200x600")
        self.master.title("Tasklister 8000")

    def create_entry(self):
        entry = self.entry.get()
        self.newTask = tk.Button(self.frame, text=entry, command = 'delete_entry')
        self.newTask.grid(columnspan=2)

    def delete_entry(self):
        self.newTask.destroy()


def main():
    root = tk.Tk()
    app = MainApplication(root)
    app.mainloop()

if __name__ == '__main__':
    main()

If root is a Tkinter object, then shouldn't I be able to call mainloop() on the class MainApplication that I made?

Thanks very much in advance for any help or even any direction to other literature!!

Upvotes: 0

Views: 4762

Answers (1)

abarnert
abarnert

Reputation: 365697

If root is a Tkinter object, then shouldn't I be able to call mainloop() on the class MainApplication that I made?

No. root is a tkinter object, but app is not. So, you can call root.mainloop(), but you can't call app.mainloop().


Sure, your app has a bunch of tkinter objects (self.master is a Tk, self.frame is a Frame, etc.), but that doesn't mean it is one. If that isn't obvious, consider this code:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
pt = Point(2, 3)

Your pt has some integers, but that doesn't mean it is one. You wouldn't expect pt.bit_length() or pt + 6 or float(pt) to work, right?


If you've seen examples that seem similar to your code (e.g., the Effbot book is full of them), the key difference is that make MainApplication a subclass of either tkinter.Tk or tkinter.Frame. If you did that, then app would be a tkinter object (a Tk or a Frame). But you didn't.

Upvotes: 4

Related Questions