Open A Image File Then Display It In New Window
I have a button in my GUI then after selecting a image file I want it to display in new window. Code: import tkinter as tk from tkinter import * from tkinter import ttk from tki
Solution 1:
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()
defopen_img_file():
filename = filedialog.askopenfilename(initialdir=os.getcwd(
), title="Select file", filetypes=(("png images", ".png"), ("all files", "*.*")))
ifnot 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()
Solution 2:
Use this to display the image in tkinter
:
Display image :)
from tkinter import *
defmakeLabel(parent, image):
# Make label to display the image
label = Label(parent, image=image)
label.pack()
defshowImg():
# 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()
Also you can using matplotlib :)
Use library
It's cool ^_^
You can display an image very simply by using matplotlib
:
import matplotlib.pyplotas plt
import matplotlib.imageas mpimg
img = mpimg.imread('YOUR_PIC.png')
imgplot = plt.imshow(img)
plt.show()
Install library
But install it before using it :)
python2:
pip2 install matplotlib
python3:
pip3 install matplotlib
Post a Comment for "Open A Image File Then Display It In New Window"