Python print statement changes behavior of code?

生来就可爱ヽ(ⅴ<●) 提交于 2020-07-09 16:57:24

问题


The weirdness: After some experimenting I've concluded that putting in a useless line (print "hi", or x = 1) ANYWHERE in the code below makes it work correctly.

What's going on? I'd love to understand what about how Python is processing this code that's causing this weird behavior.

Some context: I'm writing a gui in wxpython. I have this function (see below) which causes a tool to change icons when pressed (by removing the tool and adding it back in with a different icon).

The code shown below causes the button to switch icons correctly the first time, then the second time the toolbar seems to come up disabled. I had assumed it was a problem with the code, so I put in a print statement, which, to my surprise, fixed the problem.

def configure_itunes_button(self):
    '''
    Configures the itunes button to either sync or unsync depending on whether itunes is currently synced
    '''
    if self.iTunesTool:
        id = self.iTunesTool.GetId()
        self.toolbar.DeleteTool(id)
    else:
        id = self.toolbar.GetToolsCount() + 1

    if self._is_itunes_synced_locally:
        self.iTunesTool = self.toolbar.AddSimpleTool(id, wx.Bitmap('images\\iTunes.png'), "Sync iTunes Library", "Sync all iTunes music and playlists to Sookbox.")
    else:
        self.iTunesTool = self.toolbar.AddSimpleTool(id, wx.Bitmap('images\\trash.gif'), "Stop syncing iTunes Library", "Stop syncing all iTunes music and playlists to Sookbox.")

    self.Bind(wx.EVT_TOOL, self.onITunesSync, self.iTunesTool)
    self.toolbar.Realize()

回答1:


I would try using SetToolNormalBitmap rather than deleting the button. Then call toolbar.Realize(). See also https://groups.google.com/forum/#!topic/wxpython-users/m11YfTdjVjw

You may need to call self.Layout or self.Refresh too.

Alternatively, you might want to take a look at FlatMenu which is a pure Python implementation of the wxPython menu and toolbar. It would allow easier hacking.



来源:https://stackoverflow.com/questions/18234228/python-print-statement-changes-behavior-of-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!