使用Python的Graphics.py绘制康托尔集时窗口崩溃无报错的问题
Hey there, let's break down why your Cantor Set code is causing the window to act like it's crashing, and fix the drawing logic at the same time:
Two Key Problems in Your Code
Incorrect Integer Division Order
In your second recursive call,x+Len*(2//3)is the main issue. Since2//3evaluates to 0 in integer division, this means you're drawing the right segment starting at the exact same x-position as the left one. Not only does this make your Cantor Set look completely wrong (all segments pile up on the left), but rendering all those overlapping lines can put unnecessary strain on the graphics library, contributing to that weird crash-like behavior.Window Closes Instantly
After your code finishes drawing, the program exits right away, so theGraphWinwindow closes immediately. It's not actually crashing—it just doesn't wait for you to see the result!
Fixed Code
from graphics import * def cantor_set(win, x, y, h, Len): if Len < 2: return line = Line(Point(x, y), Point(x+Len, y)) line.setWidth(10) line.draw(win) # Recurse on the left third of the segment cantor_set(win, x, y+h, h, Len//3) # Recurse on the right third - fixed position calculation cantor_set(win, x + (2 * Len) // 3, y+h, h, Len//3) def cantor_set_starter(): win = GraphWin("Cantor Set", 500, 250) cantor_set(win,5,10,20,490) # Wait for user click before closing the window win.getMouse() win.close() cantor_set_starter()
What Changed?
- Fixed the right segment position: Swapped the order of operations to
x + (2 * Len) // 3—now we first calculate twice the total length, then divide by 3, giving the correct starting point for the right third of the segment. - Added window wait: The
win.getMouse()line keeps the window open until you click anywhere inside it, so you can actually see the complete Cantor Set you drew.
内容的提问来源于stack exchange,提问作者SneakyCanuck

