Paul Jones
Paul Jones

Reputation: 149

How do I create a Tkinter canvas from an object creation?

I am trying to figure out how to make manageable object oriented applications in python using my knowledge of what I learned to do for Java in university.

I have 2 python files in my program directory, app.py as the driver and canvas.py to create the Tkinter GUI for the program. It's a rather simple GUI of only 2 buttons where I want one button to close the program and one button to use the getCommand() method in app.py. The problem is when I create my canvas object in app.py I get the error method:

TypeError: 'module' object is not callable

Here is the code in canvas.py: import tkinter as tk

class canvas:

def __init__():
    root =tk.Tk()
    root.geometry("400x400")
    frame = tk.Frame(self)
    tk.Button(frame, text="Speak", command=getCommand).pack(side=tk.LEFT)
    tk.Button(frame, text="Quit", command=quit).pack(side=tk.LEFT)
    frame.pack()

and in app.py I create the object with

root = canvas()
root.mainloop()

Any tips and answers on what I should do are appreciated!

Upvotes: 0

Views: 652

Answers (1)

yuvgin
yuvgin

Reputation: 1362

In order to create a new instance of the class canvas, you need to use the syntax canvas.canvas(), since canvas is both the name of the class and the name of the constructor method (as mentioned).

However note that as of now you set the variable root to be an instance of the class canvas, and thus root.mainloop() will not run as expected, since canvas is not a Tkinter root. I recommend the following:

In your canvas class:

class canvas:

def __init__(self, root):
    self.root = root
    self.root.geometry("400x400")
    self.frame = tk.Frame(self)
    self.tk.Button(frame, text="Speak", command=getCommand).pack(side=tk.LEFT)
    self.tk.Button(frame, text="Quit", command=quit).pack(side=tk.LEFT)
    self.frame.pack()

Then in app.py:

root = tk.Tk()
canvas = canvas.canvas(root) # note proper const. of canvas instance
root.mainloop()

Another side note: if you plan on using Python long-term, it is well advised to keep with Python code style conventions (e.g PEP-8). In this case, class names should begin with capital letters, and method/function names should be all lowercase with underscores ('_') used for clarity as necessary. This is opposed to camelcase (e.g someFunction) which is common in Java.

Upvotes: 3

Related Questions