我在GUI中有一个按钮,然后选择了图像文件后,我希望它在新窗口中显示。
代码:
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()
答案 0 :(得分:1)
要使其正常工作,您需要在命令功能中对此进行初始化:
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()
答案 1 :(得分:0)
tkinter
中显示图像:显示图像:)
from tkinter import * def makeLabel(parent, image): # Make label to display the image label = Label(parent, image=image) label.pack() def showImg(): # Define root window! root = Tk() # Bring the image to the script! img = PhotoImage(file='YOUR_PIC.png') # Show image as label makeLabel(root, img) # Update root (GUI) root.mainloop() if __name__ == '__main__': showImg()
太酷了^ _ ^
您可以使用matplotlib
非常简单地显示图像:
import matplotlib.pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('YOUR_PIC.png') imgplot = plt.imshow(img) plt.show()
但是在使用它之前先安装它:)
python2:
pip2 install matplotlib
python3:
pip3 install matplotlib