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")andd = win.setBackground("DeepSkyBlue"), but thesetBackground()method doesn't return a useful value (it actually returnsNone). - When you check
if userinput == n, you're comparing the input string"n"toNone—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
userinputdirectly 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 (likeNinstead ofn). - Added an
elsecase 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
相关产品推荐
相关产品推荐

