我对Python很新,所以我希望你原谅我这样的业余代码。我已经尝试过做类似事情的例子,但我很难弄清楚他们在做什么,这是不同的。在示例中,我看到使用循环生成的每个按钮都有不同的动作,因为我只有循环中的最后一个按钮受到点击的影响,无论我按哪个按钮。这是代码:
import wx
import mmap
class pt:
Note = open('note.txt', "r+")
buf = mmap.mmap(Note.fileno(), 0)
TL = 0
readline = buf.readline
while readline():
TL += 1
class MainWindow(wx.Frame):
def __init__(self, parent, title):
w, h = wx.GetDisplaySize()
x = w * 0
y = h - bdepth
wx.Frame.__init__(self, parent, title = title, pos = (x, y), size = (200,bdepth), style = wx.STAY_ON_TOP)
self.__DoLayout()
self.Bind(wx.EVT_BUTTON, self.OnClick)
self.Show(True)
def __DoLayout(self):
self.__DoButtons(wx.Panel(self, size=(200,bdepth), pos=(0,0), name='panel'), 'Cheese')
def __DoButtons(self, panel, label):
for i, line in enumerate(pt.Note):
solid = wx.EmptyBitmap(200,50,-1)
dc = wx.MemoryDC()
dc.SelectObject(solid)
solidbrush = wx.Brush(wx.Colour(75,75,75),wx.SOLID)
solidpen = wx.Pen(wx.Colour(75,75,75),wx.SOLID)
dc.SetBrush(solidbrush)
dc.SetPen(solidpen)
dc.DrawRectangle(0, 0, 200, 50)
dc.SetTextForeground(wx.Colour(255, 255, 255))
dc.DrawText(line.rstrip(), 30, 17)
dc.SelectObject(wx.NullBitmap)
self.checked = wx.Image('buttonchecked.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()
dc = wx.MemoryDC()
dc.SelectObject(self.checked)
dc.SetTextForeground(wx.Colour(200, 255, 0))
dc.DrawText(line.rstrip(), 30, 17)
dc.SelectObject(wx.NullBitmap)
self.b = wx.BitmapButton(panel, i + 800, solid, (0, i * 50), (solid.GetWidth(), solid.GetHeight()), style = wx.NO_BORDER, name=line.rstrip())
def OnClick(self, event):
self.b.SetBitmapDisabled(self.checked)
self.b.Enable(False)
print('cheese')
bdepth = pt.TL * 50
app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()enter code here
答案 0 :(得分:1)
只有最后一个按钮正常工作,因为每次通过__DoButtons循环时,都会将self.b重新分配给另一个按钮。因此,循环完成后,self.b仅分配给最后一个按钮。您可以使用event.GetEventObject()方法按下按钮。
将OnClick方法更改为:
def OnClick(self, event):
button = event.GetEventObject()
button.SetBitmapDisabled(self.checked)
button.Enable(False)
print('cheese')