Tkinter Canvas是空的

时间:2013-04-14 20:13:15

标签: python canvas python-3.x tkinter

我从这里的第一个例子中获取了这段代码http://zetcode.com/gui/tkinter/drawing/我对它进行了改编,以便它可以在同一个文件中打印一个地图。没有固有的错误,它会通过循环甚至正确地命中所有if语句。但最终画布/框架中没有任何内容。谁能告诉我为什么?

from tkinter import Tk, Canvas, Frame, BOTH, NW


    class Example(Frame):

        def __init__(self, parent):
            Frame.__init__(self, parent)   

            self.parent = parent        
            self.initUI()

        def initUI(self):

            self.parent.title("Board")        
            self.pack(fill=BOTH, expand=1)

            canvas = Canvas(self)

            #The first four parameters are the x,y coordinates of the two bounding points.
            #The top-left and the bottom-right. 
            color = ""
            for x in range(10):
                for y in range(10):
                    if type(landMass[x][y]) is Land:
                        color = "grey" 
                    if type(landMass[x][y]) is Food:
                        color = "green"
                    if type(landMass[x][y]) is Water:
                        color = "blue"
                    if type(landMass[x][y]) is Shelter:
                        color = "black"
                    rec = canvas.create_rectangle(3 + 50 * y, 3 + 50 * x, 53 + 50 * y, 53 + 50 * x , fill=color)
                    text = canvas.create_text(3 + 50 * y, 3 + 50 * x, anchor=NW, fill="white", text=landMass[x][y].elevation)

    def main():

        root = Tk()
        ex = Example(root)
        root.geometry("500x500+500+500")
        root.mainloop()  


    if __name__ == '__main__':
        main() 

1 个答案:

答案 0 :(得分:3)

检查链接,您在功能结束时省略了对canvas.pack(fill=BOTH, expand=1)的调用。

此后:

for x in range(10):
    for y in range(10):
        if type(landMass[x][y]) is Land:
            color = "grey" 
        if type(landMass[x][y]) is Food:
            color = "green"
        if type(landMass[x][y]) is Water:
            color = "blue"
        if type(landMass[x][y]) is Shelter:
            color = "black"
        rec = canvas.create_rectangle(3 + 50 * y, 3 + 50 * x, 53 + 50 * y, 53 + 50 * x , fill=color)
        text = canvas.create_text(3 + 50 * y, 3 + 50 * x, anchor=NW, fill="white", text=landMass[x][y].elevation)

你应该:

canvas.pack(fill=BOTH, expand=1)