【问题标题】:Tkinter Canvas is emptyTkinter 画布为空
【发布时间】:2013-04-14 20:13:14
【问题描述】:

我从http://zetcode.com/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() 

【问题讨论】:

    标签: python canvas python-3.x tkinter


    【解决方案1】:

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

    【讨论】:

    • 不幸的是我已经尝试过了,并且链接在同一个地方有包。
    • @EasilyBaffled 你错了!我自己在您的代码上尝试过它并且它有效,它现在显示所有内容。如果你不包装画布显然不会显示它
    • @EasilyBaffled 该链接在正确的位置有pack,但你的根本没有!
    • 啊,你说得对,我知道问题出在哪里,我想念将 self.pack(fill=BOTH, expand=1) 读为 canvas.pack(fill=BOTH, expand=1),这搞砸了一切
    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 2016-05-12
    • 1970-01-01
    • 2013-05-25
    • 2013-12-28
    • 1970-01-01
    • 2020-05-15
    • 2011-09-08
    相关资源
    最近更新 更多