我正在使用 Python PIL 模块来绘制一些线条,并使用 for 循环来更改线条的宽度。但现在我想做的是,当线宽为0
时,我想要去添加lw
的值。基本上当宽度值变为零时,我希望它回到 120。
这是我的代码...
from PIL import Image, ImageDraw
img = Image.new('RGB', (2000, 2000), (0, 0, 0))
draw = ImageDraw.Draw(img)
lw = 0
for y in range(-100, 2100, 100):
lw = lw + 10
draw.line((2000, y, 0, y), (255,0,0), 120-lw)
img
这是此代码中的图像...
我正在考虑使用 if
语句,但我不知道在哪里合并它。有什么想法吗?
提前致谢!
最佳答案
for y in range(-100, 2100, 100):
lw = lw + 10
draw.line((2000, y, 0, y), (255,0,0), 120-lw)
不错的尝试。
I was thinking to use
if
statement but I don't know where to incorporate it. Any ideas?
在这种情况下,我建议这样做:
for y in range(-100, 2100, 100):
lw = lw + 10
if (lw >= 120): # When lw reaches 120...
lw = 0 # ...you set it to 0
draw.line((2000, y, 0, y), (255,0,0), 120-lw)
无论如何,一个更优雅的解决方案(不涉及 if
语句)将是这样的:
for y in range(-100, 2100, 100):
lw = lw + 10
draw.line((2000, y, 0, y), (255,0,0), 120-(lw%120))
%
运算符获取 lw/120
的余数,因此当 lw>=120
时,您不会得到更大的值无论如何,比 120
还要多。
编辑
I want to go from 120 to 0, and from 0 to 120. In this way it goes like this (120, 110,..., 20, 10, 0, 120, 110,...), but I would like to go like this (120, 110,..., 20, 10, 0, 10, 20,...,
在这种情况下,您必须使用if
语句:
incrementing = True
lw = 0
for y in range(-100, 2100, 100):
if (lw == 120):
incrementing = False
elif (lw == 0):
incrementing = True
if (incrementing):
lw = lw + 10
else:
lw = lw - 10
draw.line((2000, y, 0, y), (255,0,0), 120-lw)
我的建议是使用 bool
ean 变量来使递增/递减更容易。
关于python - 如何使python中的值变为0,使其返回到相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71973980/