I'm trying to show a picture in Tkinter using PIL. As suggested in a previous question, I use a label for this:
from Tkinter import *
class App(Frame):
def __init__(self,master):
Frame.__init__(self,master)
self.grid(row=0)
self.columnconfigure(0,weight=1)
self.rowconfigure(0,weight=1)
image = Image.load('example.png')
image = ImageTk.PhotoImage(image.convert('RGBA'))
self.display = Label(self,image=image)
self.display.grid(row=0)
root = Tk()
app = App(root)
app.mainloop()
root.destroy()
Is there a way to resize the image to fit the label? For instance, if example.png is 2000x1000 but the window is only 800x600, only a part of the image is displayed.
Tkinter is the de facto way in Python to create Graphical User interfaces (GUIs) and is included in all standard Python Distributions. In fact, it's the only framework built into the Python standard library.
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. Creating a GUI application using Tkinter is an easy task.
Tkinter is a great way to start your app development career as it is very easy and beginner-friendly. You'll be surprised to see how easy it is to build pretty cool apps using Tkinter.
If you know the size you want, use PIL to resize the image:
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid(row=0)
self.columnconfigure(0,weight=1)
self.rowconfigure(0,weight=1)
self.original = Image.open('example.png')
resized = self.original.resize((800, 600),Image.ANTIALIAS)
self.image = ImageTk.PhotoImage(resized) # Keep a reference, prevent GC
self.display = Label(self, image = self.image)
self.display.grid(row=0)
You could also use a Canvas to display the image, I like it more:
from Tkinter import *
from PIL import Image, ImageTk
class App(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.columnconfigure(0,weight=1)
self.rowconfigure(0,weight=1)
self.original = Image.open('example.png')
self.image = ImageTk.PhotoImage(self.original)
self.display = Canvas(self, bd=0, highlightthickness=0)
self.display.create_image(0, 0, image=self.image, anchor=NW, tags="IMG")
self.display.grid(row=0, sticky=W+E+N+S)
self.pack(fill=BOTH, expand=1)
self.bind("<Configure>", self.resize)
def resize(self, event):
size = (event.width, event.height)
resized = self.original.resize(size,Image.ANTIALIAS)
self.image = ImageTk.PhotoImage(resized)
self.display.delete("IMG")
self.display.create_image(0, 0, image=self.image, anchor=NW, tags="IMG")
root = Tk()
app = App(root)
app.mainloop()
root.destroy()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With