我怎么知道在我点击的地方得到一颗星星?

2024-04-25 22:47:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在点击屏幕时画星星。就像我有点明白我需要怎么做,但是我尝试过的一次没有成功,它给出了一个错误:

AttributeError: module 'turtle' has no attribute 'onScreenClick'

有时它会说我需要在其中添加“乐趣”

#2.7 Tähtikirkas yö paranneltu versio.

#Tähtikirkas yö
import turtle as t
from random import randint, random

def draw_star(points, size, col, x, y):
    t.speed(80)
    t.penup()
    t.goto(x, y)
    t.pendown
    angle = 180 - (180 / points)
    t.color(col)
    t.begin_fill()
    for i in range(points):
        t.forward(size)
        t.right(angle)
    t.end_fill()

#pääohjelma
t.Screen().bgcolor('light yellow')

while True:
    ranPts = randint(5, 5) * 2 + 1
    ranSize = randint(20, 50)
    ranCol = (random(), random (), random())
    ranX = randint(-350, 300)
    ranY = randint(-250, 250)
    draw_star(ranPts, ranSize, ranCol, ranX, ranY)

1条回答
网友
1楼 · 发布于 2024-04-25 22:47:51

screen的方法是onclick(),或者全局函数onscreenclick()。方法/函数的参数是用户单击窗口时要调用的函数之一的名称。您的函数应该采用xy参数。下面是对您的代码的修改,允许用户通过单击而不是随机操作来照亮天空:

from turtle import Screen, Turtle
from random import randint, random

def draw_star(points, size, color, x, y):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()

    angle = 180 - (180 / points)

    turtle.color(color)
    turtle.begin_fill()

    for _ in range(points):
        turtle.forward(size)
        turtle.right(angle)

    turtle.end_fill()

def click_sky(x, y):
    ranPts = randint(2, 5) * 2 + 1
    ranSize = randint(20, 50)
    ranColor = (random(), random(), random())

    draw_star(ranPts, ranSize, ranColor, x, y)

turtle = Turtle()
turtle.speed('fastest')
turtle.hideturtle()

screen = Screen()
screen.bgcolor('light yellow')
screen.onclick(click_sky)
screen.mainloop()

enter image description here

相关问题 更多 >