0

so i am trying to make a 2d "minecraft" game in python, but i just cant get an image to show up

I have this code now:

from tkinter import *
import time


class Block:
   def __init__(self, posx, posy, game):
       self.x = posx
       self.y = posy
       self.game = game
       self.grass_block = PhotoImage(file="grass_block.gif")
       print("place")
       self.image = self.game.canvas.create_image(posx, posy, image=self.grass_block, anchor="nw")
       self.hoi = self.game.canvas.create_oval(100,100,100,100, fill = "red")

   def get_image(self):
       return self.image


class Game:
    def __init__(self):
        self.tk = Tk()
        self.tk.title("MijnCraft")
        self.tk.resizable(0, 0)
        self.canvas = Canvas(self.tk, width=1000, height=1000, highlightthickness=0)
        self.canvas.pack()
        self.bg = PhotoImage(file="nacht.gif")
        self.canvas.create_image(0, 0, image=self.bg, anchor="nw")
        self.aan = True
        self.genworld()

   def genworld(self):
       print("make")
       Block(100, 100, self)

   def gameloop(self):
       while self.aan:
           self.tk.update_idletasks()
           self.tk.update()
           time.sleep(0.01)


spel = Game()
spel.gameloop()

But i just cant get a block image to show up, i just get the backgound, does someone know what i am doing wrong, (i dont get any errors)(it does print the 2 debug messages) i hope you can help!

  • Make a list of all of the `Block()` objects that you have. – TheLizzard Jun 10 '21 at 19:39
  • It actualy works! thanks! Can you also explain why? – Ryan van Vuure Jun 10 '21 at 19:48
  • If your `Block` object goes out of scope (it isn't in a variable that you can access), python deletes it from memory. It also deletes the `PhotoImage` that is inside the `Block` object. Which means that `tkinter` can no longer access the image. It is very similar to [this](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – TheLizzard Jun 10 '21 at 19:50
  • Thanks for the explenation! – Ryan van Vuure Jun 10 '21 at 20:10

1 Answers1

0

Your instance of Block is a local object that is getting destroyed when genworld returns. To prevent this, save a reference to the block. Assuming you're going to want to create more than one block, you can use a list or dictionary.

class Game:
    def __init__(self):
        self.blocks = []
        ...
    def genworld(self):
        self.blocks.append(Block(100, 100, self))
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685