无法在功能中绘制tkinter图像

时间:2016-05-13 15:18:03

标签: python tkinter tkinter-canvas

我正在制作垄断游戏,&我试图在画布上绘制图像,但只有在功能不起作用时才会起作用:

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()

目前它不会画一张照片,但是如果我记下这些评论它会起作用(没有功能) 它也发生在主循环之后,当我想绘制球员时

我真的需要它作为一个功能。该怎么办?如果你需要我可以再添加一些代码

1 个答案:

答案 0 :(得分:2)

您错过了这行代码:myCanvas.image = photo

即使在Label上绘制图像会更容易,使用此代码,您也可以使用函数make_image()在Canvas上执行此操作:

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()