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

graphics.py日夜循环功能异常求助:输入n仍执行白天循环

Fixing Your Day/Night Cycle Issue in graphics.py

Hey there! Let's break down why your night mode isn't triggering when you type n—it's a common beginner mistake with variable handling, so no worries!

What's Going Wrong in Your Code?

The core issue is how you're defining and checking your n and d variables:

  • You assigned n = win.setBackground("MidnightBlue") and d = win.setBackground("DeepSkyBlue"), but the setBackground() method doesn't return a useful value (it actually returns None).
  • When you check if userinput == n, you're comparing the input string "n" to None—this condition will never be true, so your code skips the night mode logic entirely and ends up running only day-like behavior.

Corrected Code Example

Here's a revised version that fixes the logic, with comments explaining the changes:

from graphics import *

# Initialize your window (I'm assuming you had this part already!)
win = GraphWin("Day/Night Cycle", 800, 600)
sun = Circle(Point(700, 100), 90)
sun.setFill("Yellow")
sun.draw(win)

# Get and clean up user input (handles spaces/capital letters)
userinput = input("Is it day (d) or night (n) - type d or n: ").strip().lower()

# Define your constants clearly
night_bg = "MidnightBlue"
day_bg = "DeepSkyBlue"
n_message = "Time has been set to night!"
d_message = "Time has been set to day!"

# Handle day/night logic based on input
if userinput == "n":
    print(n_message)
    win.setBackground(night_bg)
    sun.undraw()  # Hide the sun
    # Draw the moon
    moon = Circle(Point(100, 100), 90)
    moon.setFill("White")
    moon.draw(win)
elif userinput == "d":
    print(d_message)
    win.setBackground(day_bg)
    sun.draw(win)  # Ensure sun is visible
else:
    print("Invalid input! Please type 'd' or 'n'.")

# Keep window open until user clicks (optional but helpful)
win.getMouse()
win.close()

Key Changes Explained

  • We compare userinput directly to string literals ("n" and "d") instead of invalid variables.
  • Separated background color values from the setBackground() call, making the code easier to read and tweak.
  • Added .strip().lower() to handle accidental spaces or capital letters (like N instead of n).
  • Added an else case to catch invalid inputs, which helps with debugging.

Bonus: If You Wanted an Animated Cycle

If you intended the for character in range(1333) loop to animate a repeating day/night cycle, you'd need to adjust the logic to toggle between modes over time. But based on your description, the fix above will resolve the immediate issue of night mode not triggering when you select it.

内容的提问来源于stack exchange,提问作者Parham Izady

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:41:24