2017-06-04 67 views
1

我不知道为什么我的画布不显示。有一个参考,self._screen,它是pack ed,但它根本不显示。我错过了什么?为什么我的画布和/或我的照片不显示?

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); 
+0

删除'mainloop'的参数:即使用'm.mainloop()'。你也不需要结尾的分号,但它们不会伤到任何东西, – martineau

+0

我的歉意我忘了编辑那个错误 –

回答

0

你有几个我能看到的问题。 与其他编程语言不同,在代码行末尾不使用;。您不需要在功能中放置m = Map(20)root.mainloop()。您还需要定义一个tkinter窗口,以便将root = Tk()添加到程序的开头。看看下面的代码,让我知道如果你不明白的东西。

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

非常感谢!帮了很多,但我确实有一个问题。在一个时间点,我的画布没有根(我不记得确切的条件)所以,实例化根的目的是什么? –

+0

好的,所以对于tkinter你开始通过创建主要的顶层窗口来使用[Tk()](https://docs.python.org/3/library/tkinter.html#tkinter.Tk)和那么在GUI代码的底部,你必须调用'mainloop()'一次。这样做的原因是要监视GUI中发生的所有事件,以便可以与事件交互并进行更新。它有点像程序的一个大循环,因此得名。看看这个[链接](https://stackoverflow.com/questions/8683217/when-do-i-need-to-call-mainloop-in-a-tkinter-application)。有更多关于'mainloop()'的信息 –