2017-05-06 59 views
0

我想選擇從FileDialog的文件,並在GUI中顯示的畫面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() 
相關問題