python - 如何使python中的值变为0,使其返回到相同的值?

标签 python python-imaging-library

我正在使用 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 

这是此代码中的图像...

enter image description here

我正在考虑使用 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)   

我的建议是使用 boolean 变量来使递增/递减更容易。

关于python - 如何使python中的值变为0,使其返回到相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71973980/

相关文章:

python - 使用 numpy ufuncs 就地修改 Pandas 数据框

python - 如何将两个训练有素的神经网络权重矩阵合并为一个?

python - 为什么 Python pep-8 强烈建议在制表符上使用空格进行缩进?

python 2.7.2安装

python - numpy 和 pil reshape 数组

python - 为什么当我将正确的 .kv 代码放入外部 .kv 文件时,使用 screenmanager 的 .kv 代码不起作用?

python - 将url中的图像与python中文件系统中的图像进行比较

标签自动调整大小的 Python PIL 图像

python - 在python中随机选择图像内的200x200正方形

python - ImageChops.duplicate - python