2017-02-11 18 views
0

私は背景のためにいくつかのJPGファイルを利用するtkinterプログラムを書いています。しかし、私は、スクリプトが "pyinstaller"を使って.exeファイルに変換されると、tkinterウィンドウに使われる画像は.exeファイルにコンパイル/追加されないことを発見しました。Tkinterラベルでbase64でエンコードされたイメージ文字列を使用するにはどうすればよいですか?

したがって、私は外部依存関係がないようにPythonスクリプトでイメージをハードコードすることに決めました。

import base64 
base64_encodedString= ''' b'hAnNH65gHSJ ......(continues...) ''' 
datas= base64.b64decode(base64_encodedString) 

上記のコードはベース64符号化された画像データを復号化するために使用されます。この目的のために、私は次のことを行っています。 このデコードされた画像データを画像として使用し、tkinterのラベル/ボタンとして表示したいと思っています。例えば

from tkinter import * 
root=Tk() 
l=Label(root,image=image=PhotoImage(data=datas)).pack() 
root.mainloop() 

しかし、Tkinterの画像として使用するdataに格納された値を受け付けていません。

Traceback (most recent call last): 
    File "test.py", line 23, in <module> 
    l=Label(root,image=PhotoImage(data=datas)) 
    File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3394, in __init__ 

    Image.__init__(self, 'photo', name, cnf, master, **kw) 
    File "C:\Users\Admin\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 3350, in __init__ 
    self.tk.call(('image', 'create', imgtype, name,) + options) 
_tkinter.TclError: couldn't recognize image data 
+0

あなたはpython2またはpython3を使用していますか?この[質問](http://stackoverflow.com/questions/27175029/tkinter-will-not-recognize-image-data-in-base64-encoded-string)によると、python3で可能であるようです。 –

+0

@ j_4321私はPython 3を使用しています。私はその質問をチェックしましたが、私の問題を解決することはできません。 –

+0

[質問](http://stackoverflow.com/questions/27175029/tkinter-will-not-recognize-image-data-in-base64-encoded-string)に記載されているコードを試しましたか? –

答えて

1

Tkinterの(TK 8.6とPythonの3)PhotoImageクラスのみGIF、PGM/PPM及びPNG画像フォーマットを読み取ることができる - それは次のエラーが表示されます。画像を読み込むための2つの方法があります。

  • ファイルから:PhotoImage(file="path/to/image.png")
  • base64でエンコードされた文字列から:PhotoImage(data=image_data_base64_encoded_string)まず

、あなたがbase64-に画像を変換したい場合エンコードされた文字列:

import base64 

with open("path/to/image.png", "rb") as image_file: 
    image_data_base64_encoded_string = base64.b64encode(image_file.read()) 

その後のTkinterでそれを使用します。

import tkinter as tk 

root = tk.Tk() 

im = PhotoImage(data=image_data_base64_encoded_string) 

tk.Label(root, image=im).pack() 

root.mainloop() 

PhotoImageで使用する前にdatas= base64.b64decode(base64_encodedString)という文字列をデコードしたことがありますが、base64_encodedStringを直接使用してください。

+0

確かに間違いはあなたが推測していたとおり、デコードされた値を使って画像オブジェクトを作成しました。ありがとう! –

関連する問題