Python Forum

Full Version: Building command in a looping construct
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'm trying to build commands in a loop. However it isn't working. Here's what I have coded:

   for PtrI in range(1,16):
        PNGID = "self.ShowPNG"+str(PtrI)
        FID  = BASEPATH+"/graphics/CD"+str(PtrI)+".png"
        FileID = '"'+FID+'"'                     #embed double quotes in file name string (also tried w/o quotes)
        eval('PNGID+" = Gtk.Button()"')                                              #add Show png(false buttons)
        eval('"self.fixed.put("+PNGID+","+str(MAIN_WINDOW_WIDTH-120)+","+str(MAIN_WINDOW_HEIGHT-120)+")"')  #set false Button location
        eval('"self.image = Gtk.Image.new_from_file("+FileID+")"')           #set up to use a picture 4 button
        eval('PNGID+".set_image(self.image)"')                                       #set image to button
        eval('PNGID+".set_relief(Gtk.ReliefStyle.NONE)"')                            #remove the button border 2 show only png
        eval('PNGID+".set_no_show_all(True)"')                                       #display only when we specifically say to
To display I do:
ShowPtr = 8
eval('"self.ShowPNG"+str(self.ShowPtr)+".show()"')
Both the creation and the final show appear to work (no errors) yet I get nothing.

If I do a manual version such as the below it works:
    self.ShowPNG8 = Gtk.Button()                                              #add ShowPNG8(false buttons)
    self.fixed.put(self.ShowPNG8,1160,680)  #set false Button location
    self.image = Gtk.Image.new_from_file(BASEPATH+"/graphics/CD8.png")           #set up to use a picture 4 button
    self.ShowPNG8.set_image(self.image)                                       #set image to button
    self.ShowPNG8.set_relief(Gtk.ReliefStyle.NONE)                            #remove the button border 2 show only png
    self.ShowPNG8.set_no_show_all(True)                                       #display only when we specifically say to
    self.ShowPNG8.show()


Perhaps eval isn't the correct expression to use?
OMG, why do you do this? why evals? this is obvious XY problem, tell what you want to do
Create a data structure (a list or a dict) and assign your images to them. No eval needed and easy to loop over. Don't create a separate variable for each.
Thanks. I was hung up on how to create the command string when it wasn't needed. I set up a list and that is working great.