【问题标题】:Random fill colour for shapes in Python(TKinter)Python(TKinter)中形状的随机填充颜色
【发布时间】:2014-05-21 23:21:33
【问题描述】:

我想知道如何从列表中获取随机颜色以在draw_rectangle() 中使用

colors = ["red", "orange", "yellow", "green", "blue", "violet"]

canvas.create_rectangle(self.x, self.y, self.x + 60, self.y + 60, fill = random.choice(colors))

这会导致我的代码崩溃,我还能尝试什么?

【问题讨论】:

  • 你是随机导入的吗?随机导入
  • 请更具体。它是如何崩溃的?显示什么错误?

标签: python list random tkinter


【解决方案1】:
de=("%02x"%random.randint(0,255))
re=("%02x"%random.randint(0,255))
we=("%02x"%random.randint(0,255))
ge="#"
color=ge+de+re+we

并在 tkinter 中放入

fill=color

简单 你也可以制作

fill="#"+("%06x"%random.randint(0,16777215))

【讨论】:

    【解决方案2】:

    你可以像这样使用random.choice

    import random
    colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
    canvas.create_rectangle(self.x, self.y, self.x + 60, self.y + 60, fill = random.choice(colors))
    

    每当执行此代码时,这都会将随机颜色传递给fill

    【讨论】:

    • 当我尝试这个时,我的 TK 窗口崩溃了
    • 尝试将random.choice(color)的结果存储在一个变量中并打印出来。
    【解决方案3】:

    您可以使用选项,来自包random

    random.choice(color)
    

    【讨论】:

      猜你喜欢
      • 2016-02-20
      • 2013-06-27
      • 1970-01-01
      • 2020-07-01
      • 2014-05-26
      • 1970-01-01
      • 2014-10-27
      • 2018-04-02
      • 1970-01-01
      相关资源
      最近更新 更多