You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python的Graphics.py绘制康托尔集时窗口崩溃无报错的问题

Fixing Crash and Logic Issues in Python Graphics Cantor Set Implementation

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

  1. Incorrect Integer Division Order
    In your second recursive call, x+Len*(2//3) is the main issue. Since 2//3 evaluates 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.

  2. Window Closes Instantly
    After your code finishes drawing, the program exits right away, so the GraphWin window 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:37:47