如何使用乌龟在python上更改onclick的背景颜色?

时间:2018-09-24 05:51:48

标签: python turtle-graphics

我一直在尝试使用乌龟使这些颜色在背景中的每次单击时触发。如果有人可以帮助我预先感谢您的答复,那就太好了!

    import turtle
    import random


    f = turtle.pen()
    BG=turtle.Screen()
    colors = ['blue', 'red', 'yellow', 'green']
    BG.bgcolor("black")


    richard.pencolor("orange")
    richard.penup()

    def draw(x,y):
    richard.goto(x,y)
    richard.pendown()
    for x in range(360):
    richard.forward(200)
    richard.left(108)
    richard.forward(205)
    richard.left(108)
    richard.forward(210)
    richard.left(108)
    richard.forward(215)
    richard.left(1)
    richard.forward(220)
    richard.left(108)
    richard.forward(225)
    richard.left(108)
    richard.tilt(20)
    richard.speed(90)
    richard.pencolor()
    richard.pencolor(random.choice(colors))
    richard.bgcolor()
    richard.bgcolor(random.choice(colors))
    if(x % 2 ==1):
    richard.bgcolor(random.choice(colors))
    if(x % 2 ==1):
    richard.pencolor(random.choice(colors))
    richard.penup()
    BG.onclick(draw())

1 个答案:

答案 0 :(得分:0)

您的主要问题是此行:

BG.onclick(draw())

我们需要将draw函数本身传递给onclick(),而不是None返回的draw()

BG.onclick(draw)

一个简单的示例,仅在单击窗口时更改背景颜色:

from turtle import Screen, Turtle
from random import choice

COLORS = ['blue', 'red', 'yellow', 'green']

screen = Screen()
screen.bgcolor("black")

def draw(x, y):
    color = choice(COLORS)

    while color == screen.bgcolor():  # don't use same color twice in a row
        color = choice(COLORS)

    screen.bgcolor(color)

screen.onclick(draw)
screen.mainloop()