PictureBoxで画像を貼るときのファイルパスの指定方法
デザイン画面でPictureBoxを設置して、イメージファイルを選択する場合、以下のようなコードがSharpDevelopで自動生成される。しかし、このコードでは実行時にエラーになる。
# 実行時にエラーとなるコード import System.Drawing import System.Windows.Forms from System.Drawing import * from System.Windows.Forms import * class MainForm(Form): def __init__(self): self.InitializeComponent() def InitializeComponent(self): resources = System.Resources.ResourceManager("test.MainForm", System.Reflection.Assembly.GetEntryAssembly()) self._pictureBox1 = System.Windows.Forms.PictureBox() self._pictureBox1.BeginInit() self.SuspendLayout() # # pictureBox1 # self._pictureBox1.Image = resources.GetObject("pictureBox1.Image") #ここがたぶんダメ self._pictureBox1.Location = System.Drawing.Point(12, 12) self._pictureBox1.Name = "pictureBox1" self._pictureBox1.Size = System.Drawing.Size(307, 228) self._pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage self._pictureBox1.TabIndex = 0 self._pictureBox1.TabStop = False # # MainForm # self.ClientSize = System.Drawing.Size(331, 252) self.Controls.Add(self._pictureBox1) self.Name = "MainForm" self.Text = "test" self._pictureBox1.EndInit() self.ResumeLayout(False)
エラーメッセージは、以下の通り。
SystemError: 指定されたカルチャまたはニュートラル カルチャに対して適切なリソースが見つかりませんでした。"test.MainForm.resources"が適切に埋め込まれたか、実行時にアセンブリ"ipy"にリンクされたか、または必要なサテライト アセンブリが読み込まれて完全に署名されていることを確認してください。
正確な意味は判らないが、たぶんイメージファイルが見つからないということなのではないかと推測する。なぜならばコードの中でイメージファイルのパスが書かれていないので。どうしてこれでいいのか不明だが、イメージファイルのパスを陽に与えるように書きかえてみる。
イメージファイルのパスの指定方法を以下のように変更する。するとエラーとはならず画像が表示されるウィンドウが開く。
# エラーにはならず、ちゃんと動くコード import System.Drawing import System.Windows.Forms from System.Drawing import * from System.Windows.Forms import * class MainForm(Form): def __init__(self): self.InitializeComponent() def InitializeComponent(self): self._pictureBox1 = System.Windows.Forms.PictureBox() self._pictureBox1.BeginInit() self.SuspendLayout() # # pictureBox1 # # 以下3行が書き換えたところ pathToImage = "D:\\Temp\\Figure001.png" #イメージファイルのパス image = Image.FromFile(pathToImage) self._pictureBox1.Image = image #これでイメージファイルを指定 # self._pictureBox1.Location = System.Drawing.Point(12, 12) self._pictureBox1.Name = "pictureBox1" self._pictureBox1.Size = System.Drawing.Size(307, 228) self._pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage self._pictureBox1.TabIndex = 0 self._pictureBox1.TabStop = False # # MainForm # self.ClientSize = System.Drawing.Size(331, 252) self.Controls.Add(self._pictureBox1) self.Name = "MainForm" self.Text = "test" self._pictureBox1.EndInit() self.ResumeLayout(False)