简体   繁体   中英

Why my code doesn't work?

Why doesn't this work?

for i in [a, b, c]:
    i.SetBitmap(wx.Bitmap(VarFiles[str(i)]))

I get:

Traceback (most recent call last):
  File "<string>", line 11, in ?
  File "codecc.py", line 724, in ?
    app = MyApp(0)   # stdio to console; nothing = stdio to its own window
  File "C:\Program Files (x86)\WorldViz\Vizard30\bin\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 7978, in __init__
    self._BootstrapApp()
  File "C:\Program Files (x86)\WorldViz\Vizard30\bin\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 7552, in _BootstrapApp
    return _core_.PyApp__BootstrapApp(*args, **kwargs)
  File "codecc.py", line 719, in OnInit
    frame = VFrame(parent=None)
  File "codecc.py", line 374, in __init__
    i.SetBitmap(wx.Bitmap(VarFiles[str(i)]))
KeyError: "<wx._core.MenuItem; proxy of <Swig Object of type 'wxMenuItem *' at 0x165aeab0> >"

Interestingly, this works:

 i.SetBitmap(wx.Bitmap(VarFiles["i"])) 

but this doesn't:

 i.SetBitmap(wx.Bitmap(VarFiles[i]))

The last one returns an wxpython object with the same name as i , thus breaking the loop. So I need to find a way of returning the name of this object. But i.__name__ doesn't work.

As the traceback says you have a KeyError . Since i is an object when you do str(i) you get "<wx._core.MenuItem; proxy of <Swig Object of type 'wxMenuItem *' at 0x165aeab0> >" , such key doesn't exist in a VarFiles container.

It has nothing whatsoever to do with the for loop or the way you write your list.

Break it down using a single case. Where is the error in this?

s = str(a)
v = VarFiles[s]
w = wx.Bitmap(v)
a.SetBitmap(w)

This is how I """"fixed"""" my code:

    list_a = [a, b, c]
    list_b = ["a", "b", "c"]
    [i.SetBitmap(wx.Bitmap(VarFiles[list_b[list_a.index(i)]])) for i in list_a]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM