如何在 turtle onclick 函数中为列表赋值

How to assign values to list in turtle onclick function

在我使用 python 的第一个(有趣的)项目中,我正在努力解决这个问题:我有四只海龟,它们在点击时会循环显示一组颜色状态。我需要找到一种方法将每只海龟的最后颜色状态反馈给我的程序。颜色将用作用户输入。 所以我为每个 onclick 设置了一个列表、海龟和一个单独的函数,就像这样(缩短的例子):

u_choice = [a, b, c, d]

def color_change_one(x, y):
    global u_choice
    if t_one.color() == ('grey', 'grey'):
        t_one.color('red')
        u_choice[0] = 'red'
    elif t_one.color() == ('red', 'red'):
        t_one.color('blue')
        u_choice[0] = 'blue'    

t_one = turtle.Turtle()
t_one.shape('circle')
t_one.color('grey')
t_one.onclick(color_change_one)

效果不错的是点击时颜色会发生变化,但 u_choice 不会更新。那么我在这里做错了什么?

当我运行这个:

import turtle
u_choice = ['blfsd']

def color_change_one(x, y):
    global u_choice
    if t_one.color() == ('grey', 'grey'):
        t_one.color('red')
        u_choice[0] = 'red'
    elif t_one.color() == ('red', 'red'):
        t_one.color('blue')
        u_choice[0] = 'blue'
    print u_choice

t_one = turtle.Turtle()
t_one.shape('circle')
t_one.color('grey')
t_one.onclick(color_change_one)
turtle.mainloop()

我看到 u_choice 每次点击后更新。如果您在单击海龟之前检查 u_choice 的值,那么它还没有更新 u_choice 是有道理的。

不需要您的 global u_choice 语句,因为您没有更改 u_choice 的值,只是更改其元素之一。此外,只测试 .pencolor() 更简单,因为 .color() 会更新笔和填充颜色。

尝试对您的代码进行此修改。它使用计时器作为 u_choice 变量的独立打印机。当您在乌龟的三种颜色之间循环时,您应该会在控制台上看到变化:

from turtle import Turtle, Screen

u_choice = ['a', 'b', 'c', 'd']

def color_change_one(x, y):
    if t_one.pencolor() == 'grey':
        t_one.color('red')
    elif t_one.pencolor() == 'red':
        t_one.color('blue')
    elif t_one.pencolor() == 'blue':
        t_one.color('grey')

    u_choice[0] = t_one.pencolor()

screen = Screen()

t_one = Turtle('circle')
t_one.color('grey')
u_choice[0] = t_one.pencolor()

t_one.onclick(color_change_one)

def display():
    print(u_choice)
    screen.ontimer(display, 1000)

display()

screen.mainloop()