Home > Software design >  Open an image when requested
Open an image when requested

Time:07-09

I'm trying to do a silly little program that will let me open an image given a specific number.

import os

c1= os.startfile('Cat1.PNG')
c2= os.startfile('Cat2.PNG')
c3= os.startfile('Cat3.PNG')


catlist= [c1,c2,c3]
valid= False
def cats(valid):
    while not valid:
        try:
            answer=int(input('Choose a number between 1 and 3'))
            valid= True
        except ValueError:
            print("This is not a number")
    
    if answer >=1 and answer <=3:
        print(catlist[answer-1])
    else:
        print('Wrong value')
        del (answer)
        cats(valid)
    return

cats(valid)

My problem is that my pictures just get all open when I start the program, while I want to open them when I choose a specific number.

CodePudding user response:

The problem with your code is in the part where you assign the os.startfile() function to a variable. When Python interpreter goes through your code, as soon as it hits the c1= os.startfile('Cat1.PNG') line of code, it executes the command and opens the files immediately.

import os
valid = True

def cats(valid):
    while valid:
        try:
            x = int(input("Enter a number here: "))
            valid = False

        except ValueError:
            print("This is not a number!")

        if x == 1:
            os.startfile('1.jpg')
        elif x == 2:
            os.startfile('2.jpg')
        elif x == 3:
            os.startfile('3.jpg')
        else:
            print("Wrong value")
            valid = True

cats(valid)

There is probably a better and more efficient way to do it, but here is a solution I came up with.

  • Related