简体   繁体   English

为什么我的代码在 Python 图形中执行时间过长?

[英]why my code takes too long to execute in Python graphics?

I'm trying to draw a specific pattern in a 100x100 window using John Zelle's graphics module, however, my code runs really slowly and executes the program partly.我正在尝试使用 John Zelle 的图形模块在 100x100 window 中绘制特定图案,但是,我的代码运行速度非常慢并且部分执行了程序。 I am sure that the nested for loop is not the most efficient way to do it, but I don't know any other way to alternate the colors我确信嵌套 for 循环不是最有效的方法,但我不知道有任何其他方法可以替代 colors

. . Any thoughts?有什么想法吗? Here is the code:这是代码:

 from graphics import* def drawCircle(win,center,radius,colour): c = Circle(center,radius) c.draw(win) c.setFill(colour) return(c) def drawFourcircleTF(win,x,y,color,color2): square = drawsquare(x,y,win,color2) for X in range(x+5,x+20,10): for Y in range(y+5,y+20,10): circle = drawCircle(win,Point(X,Y),5,color) def drawsquare(x1,y1,win,color): r = Rectangle(Point(x1,y1),Point(x1+20,y1+20)) r.draw(win) r.setOutline(color) r.setFill(color) return r def Penultimatedigitdesign(x,y,win,color): for Y in range(y,y+100,40): for X in range(x+20,x+100,40): drawFourcircleTF(win,X,Y,"white",color) for X in range(x,x+100,40): drawFourcircleTF(win,X,Y,color,"white") for Y in range(y+20,y+100,40): for X in range(x+20,x+100,40): drawFourcircleTF(win,X,Y,color,"white") for X in range(x,x+100,40): drawFourcircleTF(win,X,Y,"white",color)

This is the pattern I'm trying to do: enter image description here这是我想要做的模式:在此处输入图像描述

Your code works.您的代码有效。 It's just you don't call your Penultimatedigitdesign function (at least in the above snippet).只是你没有调用你的Penultimatedigitdesign function(至少在上面的代码段中)。 Also, allow the program to wait for the window to be visible.此外,让程序等待 window 可见。

Considering the snippet is in a ( .py ) file (in my case, it's code00.py ), add these lines at the end of it (the __main__ part doesn't need to be so complex, it's just some template that I use):考虑到该片段位于( .py )文件中(在我的情况下,它是code00.py ),在它的末尾添加这些行( __main__部分不需要那么复杂,它只是我使用的一些模板):

def main(*argv):
    win = GraphWin("Pattern", 200, 200)
    Penultimatedigitdesign(50, 50, win, "red")
    input("Press <Enter> to exit...")


if __name__ == "__main__":
    print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
                                                   64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    rc = main(*sys.argv[1:])
    print("\nDone.")
    sys.exit(rc)

图像0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM