简体   繁体   English

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

[英]How do I change the background color onclick on python using turtle?

I've been trying to get these colors to trigger with each click in the background using turtle. 我一直在尝试使用乌龟在背景中的每次单击时触发这些颜色。 It would be great if someone could help me thank you in advance for your responses! 如果有人可以帮助我提前感谢您的答复,那将是非常不错的!

    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())

Your main issue is this line: 您的主要问题是以下行:

BG.onclick(draw())

We need to pass the draw function itself to onclick() , not the None that draw() returns: 我们需要将draw函数本身传递给onclick() ,而不是draw()返回的None

BG.onclick(draw)

A simple example that just changes the background color when the window is clicked: 一个简单的示例,仅在单击窗口时更改背景颜色:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM