Tkinter画布是空的

2024-05-15 23:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我从这里的第一个示例中获取了这段代码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() 

Tags: thetextselfifismaindeftype
1条回答
网友
1楼 · 发布于 2024-05-15 23:24:36

检查链接,您忽略了在函数末尾对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)

你应该有:

^{pr2}$

相关问题 更多 >