2013-04-14 99 views
0

我從這裏的第一個例子中取出這個代碼http://zetcode.com/gui/tkinter/drawing/我重新修改它,以便它將在同一個文件中打印一張地圖。沒有固有的錯誤,它通過循環,甚至正確地擊中所有的if語句。但最終畫布/畫框沒有任何內容。誰能告訴我爲什麼?Tkinter帆布是空的

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

回答

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

不幸的是,我已經試過了,和鏈接在同一個地方的包。 – EasilyBaffled

+0

@EasilyBaffled你錯了!我已經在你的代碼中自己嘗試過了,它可以工作,它在完成之後現在顯示所有內容。如果你不包裝畫布顯然不會顯示它 – jamylak

+0

@EasilyBaffled鏈接在正確的地方有'pack',但是你根本沒有! – jamylak