按下按钮后如何打开文件对话框?

时间:2018-12-24 11:07:27

标签: python canvas tkinter python-imaging-library openfiledialog

我想在按下按钮后打开文件对话框。然后,我可以选择一个图像并将其显示在画布上。 (我的目标是做一个非常简单的图像编辑器)不幸的是,当我启动程序时,文件对话框会自动打开。有没有办法例如执行以下操作:

  • 按下按钮以打开文件对话框

  • 选择图片

  • 在画布上显示图像

这是我到目前为止完成的代码

from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog

root = Tk()   
#function to select my image by using the filedialog
def select_image(): 
    file_path = filedialog.askopenfilename()
    return Image.open(file_path)

#button to press to open filedialog
select = Button(root, text="select an image", command=select_image)
select.pack()

#the canvas where the image will be display
canvas = Canvas(root, width= 400, height=400, bg="grey")
canvas.pack()

image_tk = ImageTk.PhotoImage(select_image())
canvas.create_image(200,200, image= image_tk)   
root.mainloop()

1 个答案:

答案 0 :(得分:1)

由于以下这一行而打开文件对话框:

image_tk = ImageTk.PhotoImage(select_image())

我的解决方法是:

from tkinter import Tk, filedialog, Frame, Button, Canvas
from PIL import Image, ImageTk

class Gui:
    def __init__(self, master):
        self.master = master
        self.create_widgets()

    def create_widgets(self):
        self.select = Button(self.master, text="select an image", command=self.select_image)
        self.select.pack()
        self.canvas = Canvas(self.master, width= 400, height=400, bg="grey")
        self.canvas.pack()

    def select_image(self): 
        file_path = filedialog.askopenfilename()
        des = Image.open(file_path)
        bg_image = ImageTk.PhotoImage(des)
        self.canvas.bg_image = bg_image
        self.canvas.create_image(200,200, image=self.canvas.bg_image)

if __name__ == "__main__":  
    root = Tk()
    my_gui = Gui(root)
    root.mainloop()