I'm new to Python GUI's and am currently trying to build an app with DearPy. I was wondering if it's possible to use an mp4 formatted logo (animated logo) instead of the png logo's it would usually accept. For example:
with window("Appi", width= 520, height=677):
print("GUI is running")
set_window_pos("Appi", 0, 0)
add_drawing("logo", width=520, height=290)
draw_image("logo", "random.png", [0,240])
My question is: would it be possible to change the add_drawing to an add video and then the draw_image to allow me to insert an mp4 instead of a png? I've tried to look through the documentation but haven't found guidance for this yet.
Or is there an alternative package I should be using (i.e. tkinter)?
Thanks!
I used tkinter for this and it worked perfectly fine:
import tkinter as tk
import threading
import os
import time
try:
import imageio
except ModuleNotFoundError:
os.system('pip install imageio')
import imageio
from PIL import Image, ImageTk
# Settings:
video_name = 'your_video_path_here.extension' #This is your video file path
video_fps = 60
video_fps = video_fps * 1.2 # because loading the frames might take some time
try:
video = imageio.get_reader(video_name)
except:
os.system('pip install imageio-ffmpeg')
video = imageio.get_reader(video_name)
def stream(label):
'''Streams a video to a image label
label: the label used to show the image
'''
for frame in video.iter_data():
# render a frame
frame_image = ImageTk.PhotoImage(Image.fromarray(frame))
label.config(image=frame_image)
label.image = frame_image
time.sleep(1/video_fps) # wait
# GUI
root = tk.Tk()
my_label = tk.Label(root)
my_label.pack()
thread = threading.Thread(target=stream, args=(my_label,))
thread.daemon = 1
thread.start()
root.mainloop()
Edit: Thanks <3
Videos are in DearPyGui currently not supported
Related
With the following code I want to display images from a relative path .\Datasets\image_datasets\problem_datasets within my project, I am unable to do so with tkinter, Instead it displays all the images in same UI window, I want these images to be displayed like a stream of frames as a video, can you help me understand why I don't get the expected ouput.
code :
import tkinter as tk
from PIL import ImageTk, Image
from matplotlib import image
from numpy import imag
import matplotlib.pyplot as plt
import glob
root = tk.Tk()
root.title("Test app")
images = [file for file in glob.glob('.\\Datasets\\image_datasets\\problem_datasets\\*.jpg')]
for path in images:
img = ImageTk.PhotoImage(Image.open(path))
lab = tk.Label(root,image=img)
lab.photo = img
lab.pack()
root.mainloop()
A couple of points:
you dont need lab.photo = img
you need to define and pack the label outside of your loop and just overwrite the image property inside, otherwise you create new labels each iteration
i recommend using os.sep instead of hardcoded folder separators \\ to be OS-independent
to actually see the transition, you need time.sleep or similar
my example will freeze the GUI, if you want it to be reactive after launching your image-transitions/"video", you will have to implement Threads
import tkinter as tk
from PIL import ImageTk, Image
from matplotlib import image
from numpy import imag
import matplotlib.pyplot as plt
import glob
import os
import time
root = tk.Tk()
root.title("Test app")
images = [file for file in glob.glob('.' + os.sep + 'Datasets' + os.sep + 'image_datasets' + os.sep + 'problem_datasets' + os.sep + '*.jpg')]
lab = tk.Label(root)
lab.pack()
for path in images:
_img = ImageTk.PhotoImage(Image.open(path))
lab.config(image=_img)
root.update() # to update the GUI
time.sleep(0.25) # to see the transition
root.mainloop()
You created new label in each iteration of the for loop. Instead you should create the label once before the for loop and update its image inside it.
However using loop and time.sleep() is not recommended in a tkinter application, suggest to use .after() instead:
import tkinter as tk
from PIL import ImageTk, Image
import glob
root = tk.Tk()
root.title("Test app")
images = glob.glob('./Datasets/image_datasets/problem_datasets/*.jpg')
# create the label for showing the images
lab = tk.Label(root)
lab.pack()
def show_image(i=0):
if i < len(images):
img = ImageTk.PhotoImage(file=images[i])
# update image
lab.config(image=img)
lab.photo = img # save reference of image to avoid garbage collection
# can change 10(ms) to other value to suit your case
root.after(10, show_image, i+1)
show_image() # start showing the images
root.mainloop()
So i am using python 3 and got confused why the image doesnt show up in text widget after excuted the following code:
from tkinter import *
import fitz
root=Tk()
filenew=fitz.open(r'C:\Users\azoka\Desktop\Python\b.pdf')
text_1=Text(root,width=100,height=100,bg='gray').pack(side=LEFT,expand=FALSE)
def Show():
pix =filenew.getPagePixmap(0) # 0 is page number
pix1=fitz.Pixmap(pix,0)
img =pix1.getImageData("ppm")
timg=PhotoImage(data=img)
frame=[]
frame.append(timg)
text_1.image_create(END,image=timg)
Shower=Button(win1,text='show',bg='navy',fg='light cyan',width=5,height=1,command=Show)
Shower.place(x=1000,y=360)
root.mainloop()
The image just dont show up after clicked the button but it doesnt show any code error,I am new to python
and cant figure out. I want my img be shown without altering the Show()function.
-Appreciate for helpful answers!-
I tried to use the from previous code but not works
I made some fix with last version today, see fix bellow with simplifications
from tkinter import *
from PIL import Image, ImageTk
import fitz
root = Tk()
file = "yourfile.pdf"
doc = fitz.open(file)
page = doc.load_page(0) # loads page number 'pno' of the document (0-based)
pix = page.get_pixmap()
mode = "RGBA" if pix.alpha else "RGB"
img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
frame_image = ImageTk.PhotoImage(img)
label = Label(root, bg='gray')
label.pack(side=LEFT)
label.config(image=frame_image)
label.image = frame_image
root.mainloop()
requirements to use "PyMuPDF-1.21.1"
pip install --upgrade pymupdf
see more: https://pymupdf.readthedocs.io/
I would like to add a looping video in a tkinter window. I have seen codes from here in stacksoverflow and online, and they seem to be about a Live Capture Video. in my case, I would like to import a video file to my existing Tkinter window, and if possible, keep it on loop. what modules do I need to import and how do I structure the code properly?
I am gonna add some codes that I have used.. I thankfully give the credits to the original creators whoever they are.
import imageio
from PIL import Image, ImageTk
video_name = "vid.mp4"
video = imageio.get_reader(video_name)
def stream(label):
for image in video.iter_data():
frame_image = ImageTk.PhotoImage(Image.fromarray(image))
label.config(image=frame_image)
label.image = frame_image
if __name__ == "__main__":
root = Tk()
my_label = Label(root)
my_label.pack()
thread = threading.Thread(target = stream, args=(my_label))
thread.daemon = 1
thread.start()
root.mainloop()
I have an image that is saved in a file test.bmp and this file is overwritten 2 times per second
(I want to show 2 images per second).
Here is what I have so far:
import tkinter as tk
from PIL import Image, ImageTk
root = tk.Tk()
img_path = 'test.bmp'
img = ImageTk.PhotoImage(Image.open(img_path), Image.ANTIALIAS))
canvas = tk.Canvas(root, height=400, width=400)
canvas.create_image(200, 200, image=img)
canvas.pack()
root.mainloop()
But I don't know how can I refresh the image every ½ second?
I'm using Python3 and Tkinter.
Gee, the code in your question looks very familiar...
Coming up with an answer comprised of tested code was complicated by the need to have the image file be updated by some mysterious unspecified process. This is done in the code below by creating a separate thread that periodically overwrites the image file independent of the main process. I tried to delineate this code from the rest with comments because I felt it was somewhat distracting and makes things seem more complex than they are really.
The main takeaway is that you'll need to use the universal tkinter widget after() method to schedule the image to be refreshed at some future time. Care also needs to be taken to first create a place-holder canvas image object so it can be updated in-place later. This is needed because there may be other canvas objects present, and otherwise the updated image could cover them up depending on relative placement if a place-holder had not been created (so the image object id that's returned can be saved and used later to change it).
from PIL import Image, ImageTk
import tkinter as tk
#------------------------------------------------------------------------------
# Code to simulate background process periodically updating the image file.
# Note:
# It's important that this code *not* interact directly with tkinter
# stuff in the main process since it doesn't support multi-threading.
import itertools
import os
import shutil
import threading
import time
def update_image_file(dst):
""" Overwrite (or create) destination file by copying successive image
files to the destination path. Runs indefinitely.
"""
TEST_IMAGES = 'test_image1.png', 'test_image2.png', 'test_image3.png'
for src in itertools.cycle(TEST_IMAGES):
shutil.copy(src, dst)
time.sleep(.5) # pause between updates
#------------------------------------------------------------------------------
def refresh_image(canvas, img, image_path, image_id):
try:
pil_img = Image.open(image_path).resize((400,400), Image.ANTIALIAS)
img = ImageTk.PhotoImage(pil_img)
canvas.itemconfigure(image_id, image=img)
except IOError: # missing or corrupt image file
img = None
# repeat every half sec
canvas.after(500, refresh_image, canvas, img, image_path, image_id)
root = tk.Tk()
image_path = 'test.png'
#------------------------------------------------------------------------------
# More code to simulate background process periodically updating the image file.
th = threading.Thread(target=update_image_file, args=(image_path,))
th.daemon = True # terminates whenever main thread does
th.start()
while not os.path.exists(image_path): # let it run until image file exists
time.sleep(.1)
#------------------------------------------------------------------------------
canvas = tk.Canvas(root, height=400, width=400)
img = None # initially only need a canvas image place-holder
image_id = canvas.create_image(200, 200, image=img)
canvas.pack()
refresh_image(canvas, img, image_path, image_id)
root.mainloop()
I have a very simple program on Ubuntu 14.04 LTS to read and display an image using OpenCV:
import cv2 #import OpenCV
img = cv2.imread('picture.jpg') #read a picture using OpenCV
cv2.imshow('image',img) # Display the picture
cv2.waitKey(0) # wait for closing
cv2.destroyAllWindows() # Ok, destroy the window
My problem:
How can I keep reading the picture in OpenCV but display it using Tkinter ?
I ask this because I want to make an interface for my program but OpenCV is not able to do it so I need Tkinter for this. However, all the image processing I must do it on the background using OpenCV. Only displaying the results must be done using Tkinter.
EDIT:
From the answer above, I change the line:
im = Image.open('slice001.hrs').convert2byte()
To:
im=cv2.imread() # (I imported cv2)
But I got an error.
I would appreciate any hints.
You might want to take a look at this one. Here is something works for me:
import numpy as np
import cv2
import Tkinter
from PIL import Image, ImageTk
# Load an color image
img = cv2.imread('img.png')
#Rearrang the color channel
b,g,r = cv2.split(img)
img = cv2.merge((r,g,b))
# A root window for displaying objects
root = Tkinter.Tk()
# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)
# Put it in the display window
Tkinter.Label(root, image=imgtk).pack()
root.mainloop() # Start the GUI
For Python3 I had to modify #Ha Dang answer:
from tkinter import *
from PIL import Image, ImageTk
import cv2
import numpy as np
image_name = 'bla.jpg'
image = cv2.imread(image_name)
#Rearrang the color channel
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))
# A root window for displaying objects
root = Tk()
# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im)
# Put it in the display window
Label(root, image=imgtk).pack()
root.mainloop() # Start the GUI
Requirements were:
pip3
numpy==1.13.1
opencv-python==3.3.0.9
Pillow==4.2.1
brew
python3
tcl-tk
For me both answers above did not work but were close. The following code did the trick for me (I also want to use place instead of pack):
from PIL import ImageTk, Image
image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
image = ImageTk.PhotoImage(image=Image.fromarray(image))
label_image = Label(self.detection, image=image)
label_image.image = image
label_image.place(x=0, y=0, anchor="w")