1

I don't know why my canvas is not displaying. There is a reference to it, self._screen, and it is being packed, but it does not display at all. What am I missing?

class Map(Frame):

    def __init__(self, size):

        Frame.__init__(self)
        self.pack()

        #images
        self.spriteDimension = 20
        self.img1 = PhotoImage(file="Terrain1.gif")
        self.img2 = PhotoImage(file="Terrain2.gif")

        #grid
        self._mapSize = size
        # self._grid = self.randomize()

        #canvas
        canvas_dimension = self._mapSize * self.spriteDimension

        self._screen = Canvas(self, width=canvas_dimension, height=canvas_dimension)
        self._screen.pack()

        self.test()

    def test(self):
        print("in here")
        self._screen.create_image((50,50), anchor = NW, image = self.img1)
        print("out here")

def main():

    m =Map(20);
    m.mainloop(20);
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

0

You have a few problems from what I can see. Unlike other programming languages you don't use ; at the end of a line of code. You don't need to place m = Map(20) or root.mainloop() in a function. You also need to define a tkinter window so add root = Tk() to the start of your program. Take a look at the code below and let me know if you don't understand something.

from tkinter import *

root = Tk()

class Map(Frame):

    def __init__(self, size):

        Frame.__init__(self)
        self.pack()

        self.spriteDimension = 20
        self.img1 = PhotoImage(file="Terrain1.gif")
        self.img2 = PhotoImage(file="Terrain2.gif")

        self._mapSize = size

        canvas_dimension = self._mapSize * self.spriteDimension

        self._screen = Canvas(self, width=canvas_dimension, height=canvas_dimension)
        self._screen.pack()

        self.test()

    def test(self):
        print("in here")
        self._screen.create_image((50,50), anchor = NW, image = self.img1)
        print("out here")

m = Map(20)
root.mainloop()
Mike - SMT
  • 14,784
  • 4
  • 35
  • 79
  • Thank you so much! Helped a lot, but I do have a question. At one point in time my canvas was working without the root (I dont remember the exact conditions) So, What is the purpose of instantiated the root? – kevin frazier Jun 04 '17 at 04:38
  • ok so for tkinter you start building you GUI by creating the main toplevel window to put everything in using [Tk()](https://docs.python.org/3/library/tkinter.html#tkinter.Tk) and then at the bottom of your GUI code you must call `mainloop()` one time. The reason for this is to monitor all the events going on in the GUI so things can be interacted with and updated. Its kinda like a big loop for the program hence the name. Check out this [link](https://stackoverflow.com/questions/8683217/when-do-i-need-to-call-mainloop-in-a-tkinter-application). There is more information about `mainloop()` – Mike - SMT Jun 04 '17 at 04:48