如何从enum中获取特定字符串?

2024-03-28 17:04:04 发布

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

所以我在python中做了这个练习,在tkinter中创建一个随机数量的圆圈,并用它做一些事情,不管是什么。主要问题是,当我想要创建某个圆的实例时,我还必须随机选择一种颜色。如果给我一个列表(我后来拼命地创建了这个列表),然后在random.randint(0,len(list)-1)中选择一个数字,那就没有问题了。但是我们的老师为我们开设了一门课,我只是不知道如何从中获得单一的颜色。尝试了一切,谷歌搜索了一切可能的东西,但没有找到答案。你对怎么做有什么想法吗

代码:

class Colors(Enum):
    BLUE = 'blue'
    RED = 'red'
    GREEN = 'green'
    GREY = 'grey'
    YELLOW = 'yellow'


#method of another class
def someMethod(self):
    #calculations for coordinations etc. would be here, which is unimportant for my question
    #below you can see the temporary solution with list, not using that enum class Colors
    color = ['blue', 'red', 'green', 'grey', 'yellow']
    FallDownAtom(x, y, rad, color[random.randint(0, len(color)-1)], random.randint(3, 6), 
                 random.randint(3, 6)))

1条回答
网友
1楼 · 发布于 2024-03-28 17:04:04

将我的评论移至答案

import random

from enum import Enum

class Colors(Enum):
    BLUE = 'blue'
    RED = 'red'
    GREEN = 'green'
    GREY = 'grey'
    YELLOW = 'yellow'

    @classmethod
    def get(cls, val):
        if val in cls._value2member_map_:
            return cls(val)

        return None


print(Colors.BLUE.name) # BLUE
print(Colors.GREEN.value) # green - String value of the enum

print(random.choice(list(Colors))) # Random enum

print(Colors.get("grey")) # Colors.GREY

你的问题标题和描述不同,所以我打了多次电话

编辑

错误:...first choice it threw this: _tkinter.TclError: unknown color name "Colors.GREY"-这是因为您使用的是枚举,而不是字符串。您需要使用.value属性来获取枚举字符串

相关问题 更多 >