我有一个图表,当用户右键单击时会出现一个弹出菜单。子选项 A 默认选中。我希望用户能够针对不同的行为切换此复选标记。因此,我想知道 A 是否已经被检查,并且我希望在它自己的函数中处理它。让我们调用创建菜单的函数 showPopupMenu() 和需要知道 A commandA() 的检查状态的函数。
现在,如果我默认检查 A 并打印出 A 的 IsChecked() 状态,则在 showPopupMenu() 中值为 True,而在 commandA() 中值为 false。如果默认情况下未选中 A,则答案是相反的 - showPopupMenu() 将检查状态显示为 false,commandA() 将其显示为 true。这使得 commandA() 中的 IsChecked() 状态看起来与 showPopupMenu() 中的 IsChecked() 状态相反。为什么是这样?
import wxversion
wxversion.ensureMinimal('2.8')
from numpy import arange, sin, pi
import matplotlib
matplotlib.use('WX')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure
import wx
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,
'Example Frame',size=(550,350))
self.SetBackgroundColour(wx.NamedColor("WHITE"))
self.figure = Figure()
self.axes = self.figure.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)
self.axes.plot(t,s)
self.canvas = FigureCanvas(self, -1, self.figure)
self.canvas.Bind(wx.EVT_RIGHT_DOWN,
self.showPopupMenu)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.SetSizer(self.sizer)
self.Fit()
def showPopupMenu(self, event):
if not hasattr(self, "popupTwo"):
self.popupOne = wx.NewId()
self.popupTwo = wx.NewId()
self.popupThree = wx.NewId()
self.popupA = wx.NewId()
self.popupB = wx.NewId()
self.popupOne = wx.Menu()
my_a = self.popupOne.Append(self.popupA, "A", kind=wx.ITEM_CHECK)
self.popupOne.Append(self.popupB, "B")
self.popupOne.Check(self.popupA, True)
#self.popupOne.Check(self.popupA, False)
print "in showPopupMenu(): ",self.popupOne.IsChecked(self.popupA)
self.Bind(wx.EVT_MENU, self.commandA, my_a)
menu = wx.Menu()
menu.AppendMenu(-1, 'One', self.popupOne)
menu.Append(self.popupTwo, "Two")
menu.Append(self.popupThree, "Three")
self.PopupMenu(menu)
menu.Destroy()
def commandA(self, event):
print "in commandA(): ", self.popupOne.IsChecked(self.popupA)
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()
此脚本的输出:
在 showPopupMenu() 中:真
在命令A()中:假