简体   繁体   中英

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. 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

. 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). Also, allow the program to wait for the window to be visible.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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