I want to use Tkinter to display all the pictures in a specific directory, so I firstly code to show all the pictures from a given list
The code is:
import os
from Tkinter import *
from PIL import Image, ImageTk
class Application(Frame):
def add_pic_panel(self, pic):
img = ImageTk.PhotoImage(Image.open(pic))
label = Label(root, image = img)
print label
return label
def create_gui(self):
pics = ['1.jpg', '2.jpg']
for pic in pics:
self.add_pic_panel(pic)
pass
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.create_gui()
root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()
Environment: Mac OS 10.9, Python 2.7.5
How could I display all the pictures in the list?
The code does not pack the label.
Should keep the reference for the image.
def add_pic_panel(self, pic):
img = ImageTk.PhotoImage(Image.open(pic))
label = Label(self.master, image=img)
label.img = img # to keep the reference for the image.
label.pack() # <--- pack
return label
BTW, add_pic_panel use root directly. It would be better to use self.master.
root.destroy() at the last line cause TclError when closing the window. Remove the line.
Related
I'm making a program with Tkinter, I decided to use image buttons for easier to interact but PhotoImage by somehow not worked.
The code example of the script contain image button:
from tkinter import *
class test:
def __init__(self,master):
self.master = master
img = PhotoImage(r'E:\v1.1\import.png')
b1 = Button(self.master, image = img).pack()
The script that contain source code that will load the above script:
from test2 import *
maingui = Tk()
gui = test(maingui)
maingui.mainloop()
By somehow the image is not loaded, leaving very small button. Anyone know what have I wrong?
EDIT 1: I have tried this solution (mentioned by acw1668) and edit the code of the first script but its not worked
from tkinter import *
class test:
def __init__(self,master):
global img
self.master = master
img = PhotoImage('E:\\v1.1\\import.png')
imglabel = Label(image=img)
imglabel.image = img
imglabel.pack()
b1 = Button(self.master, image = img).pack()
The results is the same as you can see on the link
[1]: https://i.stack.imgur.com/Mo1XH.png
EDIT 2: I have tried to add self. into img and imglabel but its not worked too.
from tkinter import *
class test:
def __init__(self,master):
# I cannot global self.img so I have to delete it
self.master = master
self.img = PhotoImage('E:\\v1.1\\import.png')
self.imglabel = Label(image=img)
self.imglabel.image = self.img
self.imglabel.pack()
self.b1 = Button(self.master, image = self.img).pack()
Change PhotoImage from
PhotoImage('E:\\v1.1\\import.png')
to
PhotoImage( file = 'E:\\v1.1\\import.png')
I am trying to display a QR Code in a tkinter GUI, however when I execute this code:
import tkinter as tk
from PIL import Image,ImageTk
import pyqrcode
from tkinter.font import Font
import random
root=tk.Tk()
root.title("QR Lottery")
root.config(bg="white")
# Defining Fonts
TitleFont = Font(family="HEX:gon Staggered 2", size="48")
def generateQR():
num=random.randint(1,2)
if num==1:
QRCode=pyqrcode.create("You Win!")
QRCode.png("QRCode.png",scale=8)
img = Image.open('QRCode.png')
QRCodeImg = ImageTk.PhotoImage(img)
QRCodeLabel=tk.Label(image=QRCodeImg)
QRCodeLabel.grid(row=2,column=1)
else:
QRCode=pyqrcode.create("You Lose!")
QRCode.png("QRCode.png",scale=8)
img = Image.open('QRCode.png')
QRCodeImg = ImageTk.PhotoImage(img)
QRCodeLabel=tk.Label(image=QRCodeImg)
QRCodeLabel.grid(row=2,column=1)
#Labels
TitleLabel=tk.Label(text="qr lottery",bg="white",font=TitleFont)
TitleLabel.grid(row=1,column=1,columnspan=5)
ButtonQR=tk.Button(text="Generate!",bg="white",command=generateQR)
ButtonQR.grid(row=3,column=1)
root.mainloop()
The Image Label produced is a blank square. I am unsure of why this is, as I left the background color blank.
Question: The Image Label produced is a blank square. I am unsure of why this is
A:You must keep a reference to the image object in your Python program, by attaching it to another object.
Use the following:
Define your own widget QRCodeLabel by inherit from tk.Label.
Init only with parameter parent
class QRCodeLabel(tk.Label):
def __init__(self, parent, qr_data):
super().__init__(parent)
print('QRCodeLabel("{}")'.format(qr_data))
Create your QRCode with the passed qr_data and
save as PNG file.
qrcode = pyqrcode.create(qr_data)
tmp_png_file = "QRCode.png"
qrcode.png(tmp_png_file, scale=8)
Create a image object from the PNG file.
Tkinter can handle PNG image files by its own, no PIL needed.
NOTE: You have to use self.image to prevent garbage collection!
self.image = tk.PhotoImage(file=tmp_png_file)
Configure this Label with the self.image
self.configure(image=self.image)
Usage:
class App(tk.Tk):
def __init__(self):
super().__init__()
buttonQR = tk.Button(text="Generate!", bg="white", command=self.generateQR)
buttonQR.grid(row=2, column=0)
self.qr_label = None
def generateQR(self):
if self.qr_label:
self.qr_label.destroy()
self.qr_label = QRCodeLabel(self, random.choice(["You Win!", "You Lose!"]))
self.qr_label.grid(row=1, column=0)
if __name__ == "__main__":
App().mainloop()
Tested with Python: 3.5
I am making a program where I need to at some point display an image onto a frame at the press of a button. I am using an object oriented approach but it won't display the image. If I do something like:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
pic = Image.open("image.jpg")
tkpic = ImageTk.PhotoImage(pic)
label = Label(root, image=tkpic)
label.pack()
root.mainloop()
that works fine. But if I create a frame and try to display the picture like this:
from tkinter import *
from PIL import Image, ImageTk
class picframe(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
button = Button(self, text="show", command=self.showpic)
button.pack()
def showpic(self):
pic = Image.open("image.jpg")
tkpic = ImageTk.PhotoImage(pic)
label = Label(self, image=tkpic)
label.pack()
root = Tk()
frame = picframe(root)
frame.pack()
root.mainloop()
When I press the button it expands the window as if it was trying to display the image but nothing shows up it just becomes a wider window. So what am I doing wrong?
Thank you in advance!
As the picture is created in a function the reference tkpic will be garbage collected when the function exits. You need to save a reference to the image:
def showpic(self):
pic = Image.open("image.jpg")
tkpic = ImageTk.PhotoImage(pic)
label = Label(self, image=tkpic)
label.image = tkpic # Save reference to image
label.pack()
Alternatively you can ensure the persistance of the image reference by making it an instance variable:
def showpic(self):
pic = Image.open("images/beer.png")
self.tkpic = ImageTk.PhotoImage(pic)
label = Label(self, image=self.tkpic)
label.pack()
I'm a beginner trying to use tkinter to create a GUI. I've adapted code from other sources for my own use.
At the moment I'm trying to display an image along with a button.
However, when running the code, only the image displays no matter where I move the button, the button isn't displayed.
Would be grateful for any help.
Additional functionality:
I'm looking to implement a function so that I can move the image around using coordinates, also a function that allows me to use .jpg instead of .png.
Thanks in advance!
Code:
from tkinter import *
from PIL import Image, ImageTk
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("WindowName")
self.pack(fill = BOTH, expand = 1)
quitButton = Button(self, text = "quit", command=self.client_exit)
quitButton.place(x=400,y=400)
self.showImg()
def client_exit(self):
exit() # Or another function
def showImg(self):
self.grid(row=0)
self.columnconfigure(0,weight=1)
self.rowconfigure(0,weight=1)
self.original = Image.open('wire.png')
resized = self.original.resize((200, 200),Image.ANTIALIAS)
self.image = ImageTk.PhotoImage(resized)
self.display = Label(self, image = self.image)
self.display.grid(row=0)
root = Tk()
root.geometry("600x600")
app = Window(root)
root.mainloop()
This question already has answers here:
Why does Tkinter image not show up if created in a function?
(5 answers)
Closed 5 years ago.
I have the following code:
from tkinter import *
import os
from PIL import ImageTk, Image
#Python3 version of PIL is Pillow
class Scope:
def __init__(self, master):
self.master = master
f = Frame(root)
self.greet_button = Button(f, text="Back", command=self.back)
self.greet_button.pack(side= LEFT)
self.greet_button = Button(f, text="Detect", command=self.detect)
self.greet_button.pack(side= LEFT)
self.close_button = Button(f, text="Continue", command=master.quit)
self.close_button.pack(side=LEFT)
photo = PhotoImage(file='demo.gif')
cv = Label(master, image=photo)
cv.pack(side= BOTTOM)
f.pack()
def greet(self):
print("Previous image...")
root = Tk()
my_gui = Scope(root)
root.mainloop()
My first problem is that when I run this, all the buttons and the window show up, but there is no image. There is a square place holder indicating that the image should be in that box, but no image actually shows. I'm able to display the image if I just type the following:
root = Tk()
photo = PhotoImage(file='demo.gif')
label = Label(root, image=photo)
label.pack()
root.mainloop()
So, I know it's possible. But I don't know what I'm doing wrong with my GUI code. I've tried debugging this quite a bit and nothing seemed to work.
A second problem is, I am completely unable to display a jpg file in a GUI. I've tried using every tutorial and nothing quite does the trick. Ideally, I'd like to just be able to display a jpg image, if that's not possible, I'll settle for displaying a gif.
Your reference to photo gets destroyed / carbage collected by Python after the class is called, so, there is nothing the label could show.
In order to avoid this, you have to maintain a steady reference to it, i.e. by naming it self.photo:
from tkinter import *
import os
from PIL import ImageTk, Image
#Python3 version of PIL is Pillow
class Scope:
def __init__(self, master):
self.master = master
f = Frame(root)
self.greet_button = Button(f, text="Back") #, command=self.back)
self.greet_button.pack(side=LEFT)
self.greet_button = Button(f, text="Detect") #, command=self.detect)
self.greet_button.pack(side=LEFT)
self.close_button = Button(f, text="Continue", command=master.quit)
self.close_button.pack(side=LEFT)
self.photo = PhotoImage(file='demo.gif')
cv = Label(master, image=self.photo)
cv.pack(side=BOTTOM)
f.pack()
def greet(self):
print("Previous image...")
root = Tk()
my_gui = Scope(root)
root.mainloop()
PS: Your code snippet was not running properly because two functions were missing.