打开一个图像文件,然后在新窗口中显示 [英] Open a image file then display it in new window

查看:36
本文介绍了打开一个图像文件,然后在新窗口中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 GUI 中有一个按钮,然后在选择图像文件后我希望它显示在新窗口中.

I have a button in my GUI then after selecting a image file I want it to display in new window.

代码:

import tkinter as tk
from tkinter import *   
from tkinter import ttk
from tkinter import filedialog
import os
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
a = Tk()

def openimgfile():
    currdir = os.getcwd()
    name = filedialog.askopenfile(initialdir = currdir, title = "Select a Image", filetype = ( ("PNG", "*.png"), ("JPEG", "*.jpg;.*jpeg"), ("All files", "*.*") ) )                         

a.title("Pattern Matching")
a.minsize(200,200)
button1 = Button(text="Open file",width = 10,height =10,command=openimgfile).pack()

a.mainloop()

推荐答案

为此,您需要在命令函数中对其进行初始化:

For this to work you need to initialize this in command function:

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

window = Tk()


def open_img_file():
    filename = filedialog.askopenfilename(initialdir=os.getcwd(
    ), title="Select file", filetypes=(("png images", ".png"), ("all files", "*.*")))
    if not filename:
        return
    # setup new window
    new_window = Toplevel(window)
    # get image
    image = ImageTk.PhotoImage(Image.open(filename))
    # load image
    panel = Label(new_window, image=image)
    panel.image = image
    panel.pack()


window.title("Pattern Matching")
window.minsize(200, 200)
button = Button(text="Open file", width=10, height=10,
                command=open_img_file)
button.pack()

window.mainloop()

这篇关于打开一个图像文件,然后在新窗口中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆