0

i'm making a monopoly game, & i am trying to draw image on canvas, but it will only work if not in function:

def make_image(root, location, canvas):
photo = PhotoImage(file = root)
canvas.create_image(location["X"],location["Y"], image = photo, anchor = "nw")

class something():
def start(self, controller):
    self.controller = controller
    #photo = PhotoImage(file = "googolopoly.png")
    #self.canvas.create_image(0,0, image = photo, anchor = "nw")
    make_image("googolopoly.png", {"X":0,"Y":0}, self.canvas)
    make_text(self.canvas, "MONOPOLY!!!!", {"X":1050,"Y":20})
    make_button(self.main_tk, self.canvas, "roll dice", lambda: self.roll_dice(), {"X":1100, "Y":50}, 100)
    for i in range(controller.player_number):
        self.players.append(make_text(self.canvas, str(i+1), {"X":902+i*10, "Y":946}))
    self.main_tk.mainloop()

currently it won't draw a picture, but if i get down the comments it will work (no function) it also happens after main loop, when i want to draw players

i really need it as a function. what to do? if you need i can put some more code

Alon Kagan
  • 69
  • 9
  • you sure you want it on canvas? it would be easier to do on a Label – Liam May 13 '16 at 15:37
  • Actually I don't know what a lable is. What I wrote is what we were taught at class. If you say there is an easier solution please add an answer. (But I am using canvas for everything else) – Alon Kagan May 13 '16 at 15:55
  • Can you please post another question on how to do that with Labels? A label is a text element on the window by the way – Liam May 13 '16 at 15:57
  • What does "not work" mean? Does your program crash? Does it create the wrong image? does it create a blank image? Have you researched this? There are many questions and answers along the lines of "why doesn't my image show up when created in a function?". – Bryan Oakley May 13 '16 at 16:10
  • the image is just not shown but the program will continue to work fine @BryanOakley – Liam May 13 '16 at 16:15
  • @Bryan Oakley As Liam said – Alon Kagan May 13 '16 at 17:10

1 Answers1

3

You were missing this line of code: myCanvas.image = photo.

And even if it would be easier to draw the image on a Label, with this code you can do it on a Canvas with the function make_image():

from Tkinter import *


def make_image(filename, location, canvas):
    photo  = PhotoImage(file=filename)
    myCanvas.image = photo
    myCanvas.create_image(0,0, image = photo, anchor = "nw")



root = Tk()

myCanvas = Canvas(root, width=100, height=100)
myCanvas.grid()


make_image("image.gif", (5,5,95,95), myCanvas)

root.mainloop()
Liam
  • 6,009
  • 4
  • 39
  • 53