-1

I want my user to be able to choose from 3 (or more) options. Each of these 3 options should set the var 'bg' differently.

Here's what I have so far.

bg = 'bg.png'

#bg = 'bg.png' if line2 == 1 else 'bg2.png'
if line2 == 1:
  bg = 'bg.png'

if line2 == 2:
  bg = 'bg2.png'

if line2 == 3:
  bg = 'bg3.png'

img = Image.open(bg)
d = ImageDraw.Draw(img)

Unfortunately it doesn't work, but I hope you can see what is intended.

EDIT: I want to use the code to select an image from a TExt document. Here is the code for line2 (i.e. the 2nd line in the document):

with open("data.txt") as f:
   next(f)
   for line2 in f:
     print("---------------")
     print('Image No.:' + line2)

It prints the correct line2 number but apparently the value of 'bg' doesn't change. There is no error, but only bg.png is selected, no matter what I give as input.

jcjms
  • 41
  • 6
  • 2
    it doesn't work how? is there an error? where does line2 get set? – depperm Mar 10 '22 at 19:11
  • 3
    What is `line2`? – not_speshal Mar 10 '22 at 19:11
  • 1
    Welcome back to Stack Overflow. As a refresher, please read [ask]. "It doesn't work" is not an adequate description of the problem. Assuming that `line2` *actually has the value you expect it to have*, and that the image files in question actually exist and are in the right place, there appears to be nothing wrong with the code. However, we can't tell you whether `line2` has the correct value, because you don't show us the code that produces that value. – Karl Knechtel Mar 10 '22 at 19:14
  • Why don't you use a dict e. g. `{1:'bg.png', 2:'bg2.png', ...}` and query it by key? – KarelZe Mar 10 '22 at 19:14
  • I edited the question. – jcjms Mar 10 '22 at 19:23
  • 4
    You probably need to cast line2 to an `int` for comparison i.e. `if int(line2)==1:` – not_speshal Mar 10 '22 at 19:25

2 Answers2

0

You have to explain what you mean by "It doesn't work". but here is a better approach :

bg_options = {1: 'bg.png' , 2: 'bg2.png', 3:'bg3.png'}

with open("data.txt") as f:
   for line2 in f:
     print("---------------")
     print('Image No.:' + line2)
     bg = bg_options[int(line2)]
     img = Image.open(bg)
     d = ImageDraw.Draw(img)
eshirvana
  • 20,424
  • 3
  • 21
  • 36
  • 1
    You should well understand by now [answer]. This does not address the question that was asked; if the question actually were about how to simplify the code, it is a commonly asked question with a canonical duplicate. If something that fundamental in the question needs to be explained, the question should not be answered until that is resolved. – Karl Knechtel Mar 10 '22 at 19:16
  • I edited the question. – jcjms Mar 10 '22 at 19:23
  • @jcjms see updated answer – eshirvana Mar 10 '22 at 19:29
0

I was able to solve it with the help of @not_speshal. The only thing I had to do was swap if line2 == 1: for if int(line2)==1:. Thank you very much!

jcjms
  • 41
  • 6