Pntt
Pntt

Reputation: 93

Creating a global canvas in Tkinter Python

I am doing a simple game as a school assignment but I have problems updating my canvas. I've tried some loops and sleep commands but they don't seem to work. Now I have code that should refresh the canvas but I have no idea how to pass my canvas into my updateCanvas function.

Basically I have two functions:

def canvas(self):
    canvas = Canvas(self)
    button = Button(self, text="test", command=self.updateCanvas)
    button.place(x=240, y=5)

then I have a method that updates the canvas

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

pressing button should update canvas but it says that canvas isn't global. That makes sense. I've done java programming before. For some reason changing canvas to:

def canvas(self):
    global canvas = Canvas(self)

this gives me a "Syntax Error: invalid syntax"

What should I do? Use a loop? Can't I create a global variable inside class? Think the game as checkers or chess where I need to update the screen when a checker or piece is moved.

Upvotes: 2

Views: 1572

Answers (1)

abarnert
abarnert

Reputation: 366133

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 canvas
canvas = 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..

Upvotes: 3

Related Questions