2017-05-06 60 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() 
相关问题