我正在使用IronPython创建一个winforms应用程序。
我想知道如何获得“下一个”按钮,将PictureBox中的图像更改为列表中的下一个图像。
应用程序弹出正常,但下一个按钮不会更改图像。 但是,每次单击“下一步”按钮时,它会打印索引的新值,以进行测试。
以下是我的代码的一部分:
Images = [list, of, images]
index = 0
class IForm(Form):
def __init__(self):
self.Text = 'PictureBox'
pb = PictureBox()
pb.Parent = self
pb.Size = Size(1200, 700)
pb.Location = Point(2, 2)
pb.Image = Image.FromFile(Images[index]) #should change the image when index is changed
Next = Button()
Next.Parent = self
Next.Text = "Next >"
Next.Location = Point(1125, 905)
Next.Click += self.OnNext
self.Size = Size(1220, 970)
self.CenterToScreen()
def OnNext(self, sender, event):
global index
index += 1
print index
Application.Run(IForm())
感谢您的时间。
答案 0 :(得分:1)
您遇到的问题是pb.Image = Image.FromFile(Images[index]
不会自动再次评估,只是因为index
的值发生了变化。您必须手动执行此操作。在您的情况下,一个简单的解决方案可能看起来像这样
Images = [list, of, images]
class IForm(Form):
def __init__(self):
self.index = 0
self.Text = 'PictureBox'
self.pb = PictureBox()
self.pb.Parent = self
self.pb.Size = Size(1200, 700)
self.pb.Location = Point(2, 2)
self.pb.Image = Image.FromFile(Images[self.index])
Next = Button()
Next.Parent = self
Next.Text = "Next >"
Next.Location = Point(1125, 905)
Next.Click += self.OnNext
self.Size = Size(1220, 970)
self.CenterToScreen()
def OnNext(self, sender, event):
self.index += 1
# update the image of the PictureBox
self.pb.Image = Image.FromFile(Images[self.index])
print self.index
Application.Run(IForm())
请注意,我在此处创建了该类的pb
和index
成员变量。 pb
,因为它需要在OnNext
和index
中访问,因为您通常应该尽可能地避免global
个变量。
在更复杂的情况下,例如:当index
可以通过不同于按钮点击的方式进行更改时,您可能希望将其更改为property
并拥有更改setter方法中的图像。还有其他替代方法,例如创建OnValueChanged
回调