Creating a global canvas in Tkinter Python Creating a global canvas in Tkinter Python tkinter tkinter

Creating a global canvas in Tkinter Python


First:

global canvas = Canvas(self)

The reason this gives you a SyntaxError is that it's not valid Python.

The global statement just takes one or more names. If you want to assign anything to the name, you need a separate assignment statement:

global canvascanvas = Canvas(self)

(If you're wondering why Python is designed this way, it's not that hard to explain… but if you just want to know how to use Python, not how to design your own language, that isn't relevant here.)

However, you probably don't want to be using globals in the first place here. The whole point of classes is that their instances can have attributes, which tie together related state about something. You almost certainly want this instead:

self.canvas = Canvas(self)

And then elsewhere, in your other methods, you do things like:

self.canvas.create_oval(ovalx, ovaly, ovalx2, ovaly2, fill="black")

You may be confused because in Java, you declare instance members on the class, and then canvas magically means the same thing as this.canvas. Python doesn't work that way. Variables aren't declared anywhere, they're just created on the fly, and instance variables (and methods, too) always need an explicit self..