问题
I'm making a code so that when a user clicks on the window, it will draw the shape based on their input of choice. I'm having trouble on where I should assign the window and turtle correctly and how to assign to a function a way to quit the window its currently on. Is there any way for me to end a mainloop()
so that the user goes back to the main menu after clicking and making as many of their chosen shapes (given that each time they do choose an option, the window resets to a blank state)? If limitless clicking is not possible, then is there any way to do it but with only 1 click (then goes back to the main menu)? For simplicity, I only included one option because the other codes will be the same.
import turtle
window = turtle.Screen()
turt = turtle.Turtle()
def U(x,y):
turt.penup()
turt.setposition(x,y)
turt.pendown()
for x in range(4):
turt.forward(100)
turt.right(90)
return
def main():
global choice
if choice.upper() == "U":
window.onscreenclick(U)
window.mainloop()
run = True
print("Please choose a drawing option: 'U' or 'q' to quit.")
while run == True:
choice = str(input())
if choice.upper() != "U" and choice.lower() != "q":
print("Invalid input. Please choose either: 'U' or 'q'.")
elif choice.upper() == "U":
main()
elif choice.lower() == 'q':
run = False
回答1:
Your control logic is flawed. Turtle graphics is an event driven world so we need to put the event logic in place and then turn control over to mainloop()
to watch for keyboard and mouse events. Code like while True
and input()
conspire against this model. Here's my rework of your code to operate in an event driven way in Python 3:
from turtle import Turtle, Screen
TITLE = 'Drawing Options'
PROMPT = "Please choose a drawing option: 'U' or 'q' to quit."
def U(x, y):
window.onscreenclick(None)
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
for _ in range(4):
turtle.forward(100)
turtle.right(90)
def menu():
choice = ''
while choice not in ['U', 'u', 'Q', 'q']:
choice = window.textinput(TITLE, PROMPT) # may return None
if choice.upper() == 'U':
window.onscreenclick(U)
elif choice.lower() == 'q':
window.bye()
window.listen() # textinput() unsets this so redo
turtle = Turtle()
window = Screen()
window.onkey(menu, key='M')
window.listen()
window.mainloop()
Run it, select the window to make it the listener, then hit capital 'M' to bring up a prompt window where you can input your 'U' or 'q' commands. You can click anywhere with the mouse after the 'U' command to set a position with your square. Once this completes, you can again type capital 'M' to bring up the menu and place another square or quit.
For simplicity, I left out resetting the window to a blank state.
来源:https://stackoverflow.com/questions/47110352/end-python-turtle-drawing-so-user-goes-back-to-main-menu