[英]How to use random module to choose between three strings?
So this program prints 30 concentric circles in the middle of my canvas, I am trying to make each circle a random color using a function that I have to call, I don't really know why this doesn't work.所以这个程序在我的 canvas 中间打印了 30 个同心圆,我试图使用我必须调用的 function 使每个圆成为随机颜色,我真的不知道为什么这不起作用。 Can you tell me: A. Why doesn't this work the way it is now?
你能告诉我: A. 为什么不能像现在这样工作? B. How can I fix it?
B. 我该如何解决?
from tkinter import *
from random import *
root = Tk()
w, h = 800, 600
c = Canvas(root, width=w, height=h, bg="gold")
c.pack()
so this is the part that I need help with:所以这是我需要帮助的部分:
def colors(r = "Red", p = "Purple", b = "Blue"):
for i in range(0, 3):
choice([r, p, b])
colors("Red","Purple","Blue")
And also need help with calling the function并且还需要帮助调用 function
cx, cy = w//2, h//2
z = 5
for _ in range(30):
c.create_oval(cx-z, cy-z, cx+z, cy+z, width=2, outline = colors(r, p, b))
z += 5
Thanks a lot!非常感谢!
full code:完整代码:
from tkinter import *
from random import *
root = Tk()
w, h = 800, 600
c = Canvas(root, width=w, height=h, bg="gold")
c.pack()
def random_colors(r = "Red", p = "Purple", b = "Blue"):
for i in range(0, 3):
choice([r, p, b])
random_colors("Red","Purple","Blue")
cx, cy = w//2, h//2
z = 5
for _ in range(30):
c.create_oval(cx-z, cy-z, cx+z, cy+z, width=2, outline = choice([r,p,b])
z+= 5
root.mainloop() root.mainloop()
Let us try random.choice
:让我们试试
random.choice
:
In [28]: from random import *
...:
...: def random_colors(r, p, b):
...: r = "Red"
...: p = "Purple"
...: b = "Blue"
...: for i in range(0, 3):
...: print(choice([r, p, b]))
...:
...: random_colors("Red","Purple","Blue")
Purple
Red
Red
And are you looking for default values?您是否在寻找默认值?
from random import *
def random_colors(r = "Red", p = "Purple", b = "Blue"):
for i in range(0, 3):
print(choice([r, p, b]))
random_colors("Red","Purple","Blue")
I think you can make this better by passing your own colors as arguments我认为您可以通过将自己的 colors 传递为 arguments 来做得更好
from tkinter import *
from random import choice
root = Tk()
w, h = 800, 600
c = Canvas(root, width=w, height=h, bg="gold")
c.pack()
def colors(*args):
default = ['red','purple','blue'] # main set of colors
args = [_ for _ in args] # custom passed color
color_lst = args + default # list of all colors passed and default
color = choice(color_lst) #choosing a random color from the list
return color #returning the color
cx, cy = w//2, h//2
z = 5
for _ in range(30):
c.create_oval(cx-z, cy-z, cx+z, cy+z, width=2, outline = colors('orange','white')) #calling the function with extra 2 colors
z += 5
root.mainloop()
I've explained it with comments to make you understand while reading it.我已经用评论解释了它,以便您在阅读时理解它。 Also its better to say
from random import choice
or import random
because or else it might pollute your namespace.最好
from random import choice
或import random
导入中说,否则它可能会污染您的命名空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.