Random fill colour for shapes in Python(TKinter)

我的未来我决定 提交于 2021-02-08 05:37:02

问题


I am wondering how to get a random color out of a list to use in the 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))

This causes my code to crash, what else can I try?


回答1:


You can use random.choice like this

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

This will pass a random color to fill whenever this code is executed.




回答2:


de=("%02x"%random.randint(0,255))
re=("%02x"%random.randint(0,255))
we=("%02x"%random.randint(0,255))
ge="#"
color=ge+de+re+we

and in tkinter put

fill=color

easy you can also make

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



回答3:


You can use choice, from package random

random.choice(color)


来源:https://stackoverflow.com/questions/22950997/random-fill-colour-for-shapes-in-pythontkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!