2017-05-06 6 views
0

は私がのFileDialogからファイルを選択しようとしていると画像がGUIに示されている次の3つのステップで行うことができます達成したい何Python 3 - Tcl/Tk filedialogからイメージを取得して表示するには?

def onOpen(): 
    """ Ask the user to choose a file and change the update the value of photo""" 
    photo= get(filedialog.askopenfilename()) 

photo2 = PhotoImage(filedialog=photo) 
#how do I get photo2 to work and get button to display the picture? 
button = Button(root, image=photo2, text="click here", command=onOpen).grid() 

root.mainloop() 

答えて

1

  • はパスを取得ユーザによって選択された画像の
    filename = filedialog.askopenfilename()

  • PhotoImage

  • を作成また configure方法

を使用して、ボタンの

  • 変更画像、あなたはそれがガベージコレクトされないようにPhotoImageを含む変数をグローバルにする必要があります。

    import tkinter as tk 
    from tkinter import filedialog 
    
    def onOpen(): 
        global photo 
        filename = filedialog.askopenfilename() 
        photo = tk.PhotoImage(file=filename) 
        button.configure(image=photo) 
    
    root = tk.Tk() 
    
    photo = tk.PhotoImage(file="/path/to/initial/picture.png") 
    button = tk.Button(root, image=photo, command=onOpen) 
    button.grid() 
    
    root.mainloop() 
    
  • 関連する問題