我正在为学校做作业,想知道如何直接从海龟窗口而不是从控制台收集用户输入。海龟中是否有按钮的容量,或者如果没有,某些区域的单击事件,以便屏幕的某个区域可以充当按钮?
可以使用turtle模块提供的两种图形输入方式获取用户输入:
这些旨在帮助防止控制台样式输入需要捕获的一些错误。这些是在 Python 3 中引入的,在 Python 2 海龟中不可用。然而,在运行turtle时,您可以从Python 2调用tkinter等价物——搜索SO以获取示例。
如果您想要一个图形按钮,我的建议是您在问题上扔一只或两只乌龟以成为按钮。适当调整海龟的大小、形状和颜色,然后将
onclick()
处理程序添加到海龟上,而不是屏幕上,以便您可以单击按钮来调用操作:
from turtle import Turtle, mainloop
BUTTON_SIZE = 60
CURSOR_SIZE = 20
FONT_SIZE = 18
FONT = ('Arial', FONT_SIZE, 'bold')
STATES = (('red', 'OFF'), ('green', 'ON'))
INITIAL_STATE = STATES[0]
def toggle_power(x, y):
color, state = STATES[button.fillcolor() == 'red']
button.fillcolor(color)
marker.undo()
marker.write(state, align='center', font=FONT)
color, state = INITIAL_STATE
button = Turtle('circle')
button.shapesize(BUTTON_SIZE / CURSOR_SIZE, outline=2)
button.color('black', color)
button.penup()
# button.goto(-200, 200) # move the button into position
marker = Turtle(visible=False)
marker.penup()
marker.goto(button.xcor(), button.ycor() - BUTTON_SIZE/2 - FONT_SIZE - 2)
marker.write(state, align='center', font=FONT)
button.onclick(toggle_power)
mainloop()
上述按钮逻辑应该在 Python 3 或 Python 2 中工作。
x = screen.textinput(title="level", prompt="Which level do you want to play? Type beginner, intermediate, pro")
当您使用像 SublimeText 这样的 IDE 时,它会因常规的问题而冻结 Python input(),这可能是一个不错的选择:
import turtle as tu
tu.Screen().setup(15, 15)
# string input
name = tu.textinput("Name", "Please enter your name:")
# floating point input
age = tu.numinput("Age", "How old are you:", minval=0)
print(name)
print(age)