I mean a scroll bar that would allow you to preview the next operations. I will include lines for this example and a pictorial image. Referring to another topic and trying to solve it, I have a question. Dante would not describe what is happening in the development environment and it's hard to see without a map.
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from PIL import ImageTk
import cv2
import os
import numpy as np
history = [] # image:im , "process": p1|p2|cvt|inv|canny|... or what you want }
def showImage(canvas):
im_canvas = Image.fromarray(canvas)
imtk_canvas = ImageTk.PhotoImage(im_canvas)
lbl = Label(image=imtk_canvas)
lbl.image = imtk_canvas
lbl.pack(side="left", padx=8, pady=8)
def fSave():
savepath = filedialog.asksaveasfilename()
cv2.imwrite(savepath, history[-1]["image"])
def fOpen():
if len(history) > 0:
history.clear()
print(history)
openpath = filedialog.askopenfilename()
if os.path.isfile(openpath):
canvas = cv2.imread(openpath)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
history.insert(0, ({"image": canvas, "process": "openfile"}))
showImage(canvas)
else:
messagebox.showerror(
title="File open Error", message="The file does not exists!")
def func1():
canvas = history[0]["image"] # i tried 0 or -
print("from history type,shape ", type(canvas), canvas.shape)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2GRAY)
canvas = cv2.Canny(canvas, 30, 70)
# history.insert(0, ({"image": im2, "process": "func1"}))
history.insert(0,({"image": canvas, "process": "func1"}))
#history.append({"image": canvas, "process": "func1"})
showImage(canvas)
def func2():
canvas = history[0]["image"]
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
canvas = 255 - canvas
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
history.insert(0,({"image": canvas, "process": "func2"}))
showImage(canvas)
def set_scrollregion(self, event):
self.canvas.configure(scrollregion=self.canvas.bbox('all'))
def ini():
root = Tk()
canvas = Canvas(root)
canvas.pack(side=TOP, fill=BOTH, expand=TRUE)
xscrollbar = Scrollbar(root, orient=HORIZONTAL, command=canvas.xview)
xscrollbar.pack(side=BOTTOM, fill=X)
canvas.configure(xscrollcommand=xscrollbar.set)
frame = Frame(canvas)
canvas.create_window((0, 0), window=frame, anchor=NW)
frame.bind('<Configure>', set_scrollregion)
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Load", command=fOpen)
filemenu.add_command(label="Save", command=fSave)
filemenu.add_command(label="func1", command=func1)
filemenu.add_command(label="func2", command=func2)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
if __name__ == '__main__':
ini()
I have studied the topic, I have dug up half of the internet, documentation and there is progress, but I usually try to eliminate bugs. So that it could be scrolled sideways.
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from PIL import ImageTk
import cv2
import os
import numpy as np
history=[] #image:im , "process": p1|p2|cvt|inv|canny|... or what you want }
def showImage(canvas,lbl,side="left"):
im_canvas = Image.fromarray(canvas)
imtk_canvas = ImageTk.PhotoImage(im_canvas)
'''
lbl = Label(image=imtk_canvas)
lbl.image = imtk_canvas
lbl.pack(side="left", padx=8, pady=8)
'''
lbl.image = imtk_canvas
lbl.configure(image=imtk_canvas)
lbl.pack(side="left", padx=8, pady=8)
def fSave():
savepath = filedialog.asksaveasfilename()
cv2.imwrite(savepath, history[-1]["image"])
def fOpen(lbl,lbox):
openpath = filedialog.askopenfilename()
if os.path.isfile(openpath):
canvas = cv2.imread(openpath)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
hid = len(history)
history.append({"image":canvas,"process":"fOpen"})
lbox.insert(END, f"HistoryID:{hid} - fOpen:{openpath}")
lbox.pack()
showImage(canvas,lbl,"bottom")
else:
messagebox.showerror(
title="File open Error" , message="The file does not exists!")
def func1(lbl,lbox):
canvas = history[-1]["image"]
print("from history type,shape ",type(canvas),canvas.shape)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2GRAY)
canvas = cv2.Canny(canvas, 30, 70)
hid = len(history)
history.append({"image":canvas,"process":"func1"})
lbox.insert(END, f"HistoryID:{hid} - func1")
lbox.pack()
showImage(canvas,lbl)
def func2(lbl,lbox):
canvas = history[-1]["image"]
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
canvas = 255 - canvas
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
hid = len(history)
history.append({"image":canvas,"process":"func2"})
lbox.insert(END, f"HistoryID:{hid} - func2")
lbox.pack()
showImage(canvas,lbl)
def ini():
root = Tk()
lbox = Listbox(root, width = 640, height = 5 )
lbox.pack()
lbl1 = Label(root)
lbl1.pack()
lbl2 = Label(root)
lbl2.pack()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Load", command=lambda:fOpen(lbl1,lbox))
filemenu.add_command(label="Save", command=fSave)
filemenu.add_command(label="func1", command=lambda:func1(lbl2,lbox))
filemenu.add_command(label="func2", command=lambda:func2(lbl2,lbox))
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
if __name__ == '__main__':
ini()
In this example you can change the image of the same Label ...
# It would be better to open new questions with new posts to address different problems.
from somewhere on Stack Overflow (sorry)
import tkinter as tk
from PIL import Image
from PIL import ImageTk
path1='images/test1.png'
path2='images/test2.png'
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path1))
panel = tk.Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
def callback(e):
img2 = ImageTk.PhotoImage(Image.open(path2))
panel.configure(image=img2)
panel.image = img2
root.bind("<Return>", callback)
root.mainloop()
I mean a scroll bar that would allow you to preview the next operations. I will include lines for this example and a pictorial image. Dante would not describe what is happening in the development environment and it's hard to see without a map.
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from PIL import Image
from PIL import ImageTk
import cv2
import os
import numpy as np
history = [] # image:im , "process": p1|p2|cvt|inv|canny|... or what you want }
def showImage(canvas):
im_canvas = Image.fromarray(canvas)
imtk_canvas = ImageTk.PhotoImage(im_canvas)
lbl = Label(image=imtk_canvas)
lbl.image = imtk_canvas
lbl.pack(side="left", padx=8, pady=8)
def fSave():
savepath = filedialog.asksaveasfilename()
cv2.imwrite(savepath, history[-1]["image"])
def fOpen():
if len(history) > 0:
history.clear()
print(history)
openpath = filedialog.askopenfilename()
if os.path.isfile(openpath):
canvas = cv2.imread(openpath)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
history.insert(0, ({"image": canvas, "process": "openfile"}))
showImage(canvas)
else:
messagebox.showerror(
title="File open Error", message="The file does not exists!")
def func1():
canvas = history[0]["image"] # i tried 0 or -
print("from history type,shape ", type(canvas), canvas.shape)
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2GRAY)
canvas = cv2.Canny(canvas, 30, 70)
# history.insert(0, ({"image": im2, "process": "func1"}))
history.insert(0,({"image": canvas, "process": "func1"}))
#history.append({"image": canvas, "process": "func1"})
showImage(canvas)
def func2():
canvas = history[0]["image"]
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
canvas = 255 - canvas
canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
history.insert(0,({"image": canvas, "process": "func2"}))
showImage(canvas)
def ini():
root = Tk()
h = Scrollbar(root, orient='horizontal')
h.pack(side=BOTTOM, fill=X)
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Load", command=fOpen)
filemenu.add_command(label="Save", command=fSave)
filemenu.add_command(label="func1", command=func1)
filemenu.add_command(label="func2", command=func2)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
root.config(menu=menubar)
root.mainloop()
if __name__ == '__main__':
ini()
sample effect image
Related
I am making a simple maths game but my background is covering the labels
how do I make it so the background image still resizes to the screen but is under the labels instead?
this is my code:
import tkinter
from tkinter import *
import tkinter.font as font
from PIL import Image, ImageTk
# INITIALIZE TKINTER
root = tkinter.Tk()
root.title('Test De Multiplications')
#root.iconbitmap('')
root.geometry('600x400')
# DEFINE FONTS
labelfont = font.Font(family='Comic Sans MS', weight='bold', size='30')
normalfont = font.Font(family='Arial', size='20')
subtitle = font.Font(family='Calibri', weight='bold', size='25')
# RAISING FRAMES (Swithching windows)
def raise_frame(frame):
frame.tkraise()
f1 = Frame(root)
f2 = Frame(root)
for frame in (f1, f2):
frame.grid(row=0, column=0, sticky='news')
title = Label(f1, text="TEST DE MULTIPLICATIONS", font=labelfont)
title.pack(side= TOP, fill = BOTH, expand = True)
start = Button(f1, text='Commencer', font=normalfont, background='darkred', command=lambda:raise_frame(f2))
start.pack(side= TOP, expand= True)
playtitle = Label(f2, text='QUESTION:', font=normalfont ).pack()
raise_frame(f1)
class bg(Frame):
def __init__(self, master, *pargs):
Frame.__init__(self, master, *pargs)
self.image = Image.open("bg.ppm")
self.img_copy= self.image.copy()
self.background_image = ImageTk.PhotoImage(self.image)
self.background = Label(self, image=self.background_image)
self.background.pack(fill=BOTH, expand=YES)
self.background.bind('<Configure>', self._resize_image)
def _resize_image(self,event):
new_width = event.width
new_height = event.height
self.image = self.img_copy.resize((new_width, new_height))
self.background_image = ImageTk.PhotoImage(self.image)
self.background.configure(image = self.background_image)
e = bg(root)
e.place(x=0, y=0, relwidth=1, relheight=1)
root.mainloop()
I'm using multiple frames for the window switching so I'm wondering if that has something to do with it? I still want to be able to change windows like this, because it works well.
Here is the full code
import tkinter as tk
from PIL import ImageTk, Image
def hide_screen():
window.overrideredirect(0)
window.iconify()
def screen_appear(event):
window.overrideredirect(1)
def callback(event):
window.geometry("+{0}+{1}".format(event.x_root,event.y_root))
window = tk.Tk()
window.geometry("400x200")
window.overrideredirect(True)
title_bar = tk.Frame(window, bg="#2c2c2c", bd=0)
title_bar_logo = ImageTk.PhotoImage(Image.open("title_bar_logo.png"))
title_bar_logo = ImageTk.resize((250, 250), Image.ANTIALIAS)
panel = tk.Label(title_bar, image=title_bar_logo)
label1 = tk.Label(title_bar, text="Title Bar", fg="gold2", bg="#2c2c2c", font="Times")
close_button = tk.Button(title_bar, text="X", bg="red", command=window.destroy, bd=0)
minimise_button = tk.Button(title_bar, text="-", bg="red", command=hide_screen, bd=0)
window2 = tk.Canvas(window, bg="#1b1b1b", highlightthickness=0)
title_bar.pack(fill="x")
panel.pack(side=tk.LEFT)
close_button.pack(side=tk.RIGHT)
minimise_button.pack(side=tk.RIGHT)
window2.pack(expand=1, fill="x")
label1.pack(anchor=tk.CENTER)
title_bar.bind("<Map>", screen_appear)
title_bar.bind("<B1-Motion>", callback)
window.mainloop()
And here are the image lines
title_bar_logo = ImageTk.PhotoImage(Image.open("title_bar_logo.png"))
title_bar_logo = ImageTk.resize((250, 250), Image.ANTIALIAS)
panel = tk.Label(title_bar, image=title_bar_logo)
panel.pack(side=tk.LEFT)
i have tried soo many things but i can't get it to work
and i really hope you can find an answer for me
thank you in advance
I use it as example it working well:
logo = Image.open("title_bar_logo.png")
logo = logo.resize((20,15), Image.ANTIALIAS)
title_bar_logo=ImageTk.PhotoImage(logo)
use :
title_bar_logo
in your code
I want to add a button which can load next image file and display it to canvas. Here is the code that I have done until now. Can anyone help to add next button?
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk,Image
root = Tk()
openfile = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
img = ImageTk.PhotoImage(Image.open(openfile))
wh = img.width()
ht = img.height()
w = Canvas(root, width=wh, height=ht, bg='black')
w.pack(expand = YES)
w.create_image(0, 0, anchor=NW, image = img)
B = Button(root, text="next")
B.place(x=50, y=50)
root.mainloop()
Following script allows you to see all images in selected folder:
import os
import glob
from tkinter import filedialog
import tkinter as tk
from PIL import ImageTk, Image
class ImageViewer(object):
def __init__(self):
self.root = tk.Tk()
self.root.state('zoomed')
self.width = self.root.winfo_screenwidth()
self.height = self.root.winfo_screenheight()
self.images = None
img, wh, ht = self.open_file()
self.canvas = tk.Canvas(self.root, width=wh, height=ht, bg='black')
self.canvas.pack(expand=tk.YES)
self.image_on_canvas = self.canvas.create_image(self.width/2, self.height/2, anchor=tk.CENTER, image=img)
b = tk.Button(self.root, text='next', command=self.next_image)
b.place(x=50, y=50)
self.root.mainloop()
def open_file(self):
openfile = filedialog.askopenfilename(initialdir='/', title='Select image', filetypes=(('jpeg files', '*.jpg'), ('all files', '*.*')))
self.images = glob.glob(os.path.dirname(openfile) + '/*.jpg')
self.root.title(openfile)
img = Image.open(openfile)
img.thumbnail((self.width, self.height), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
return img, self.width, self.height
def next_image(self):
if not self.images:
img, wh, ht = self.open_file()
else:
image = self.images.pop(0)
self.root.title(image)
img = Image.open(image)
img.thumbnail((self.width, self.height), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
self.canvas.itemconfigure(self.image_on_canvas, image=img)
self.canvas.config(width=self.width, height=self.height)
try:
self.canvas.wait_visibility()
except tk.TclError:
pass
ImageViewer()
I want to print the mean, height & width of an image in python openCV. Where i used two button (get photo and analysis image) and different GUI,one for getting the photo(def openphoto(): ) and another for printing those features(def feature(): ). But I'm getting error.
N.B. full code is too long.so, i used some part of it.
I've tried it in python openCV.
import tkinter as tk
from tkinter.filedialog import askopenfilename
import shutil
import os
from PIL import Image, ImageTk
window = tk.Tk()
window.title("Dr. Papaya")
window.geometry("500x510")
window.configure(background ="lightgreen")
title = tk.Label(text="Click below to choose picture for testing disease....", background = "lightgreen", fg="Brown", font=("", 15))
title.grid()
def feature():
window.destroy()
window1 = tk.Tk()
window1.title(" ")
window1.geometry("650x510")
window1.configure(background="lightgreen")
def exit():
window1.destroy()
#i want to print here
print("Mean : ",mean)
print("Heigth : ",heigth)
print("Width : ",width)
button = tk.Button(text="Exit", command=exit)
button.grid(column=0, row=9, padx=20, pady=20)
window1.mainloop()
def openphoto():
import cv2
import numpy as np
fileList = os.listdir(dirPath)
for fileName in fileList:
os.remove(dirPath + "/" + fileName)
fileName = askopenfilename(initialdir='', title='Select image for analysis ',
filetypes=[('image files', '.jpg')])
dst = " "
shutil.copy(fileName, dst)
load = Image.open(fileName)
#calculate the mean
mean=np.mean(load)
#calculate the height & width
height = np.size(load, 0)
width = np.size(load, 1)
render = ImageTk.PhotoImage(load)
img = tk.Label(image=render, height="250", width="500")
img.image = render
img.place(x=0, y=0)
img.grid(column=0, row=1, padx=10, pady = 10)
title.destroy()
button1.destroy()
button2 = tk.Button(text="Analyse Image", command=feature)
button2.grid(column=0, row=2, padx=10, pady = 10)
button1 = tk.Button(text="Get Photo", command = openphoto)
button1.grid(column=0, row=1, padx=10, pady = 10)
window.mainloop()
The variables are not in scope when you try to print them. This is an important programming principle so I suggest you read this introduction
You can make the variable global to make the them accessible outside of the function:
def openphoto():
global width, height, mean
[rest of code]
I am trying to make a set of code that will open a window and displaying 6 images in sequence over and over again very quickly for 10 seconds. This is my code, however the program simply open a blank screen. What do I do?
import time
import tkinter as tk
root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenwidth()
root.geometry('%dx%d' % (width*1, height*1))
def SS_Part1():
image_file_ssp1 = "goat1.gif"
image = tk.PhotoImage(file=image_file_ssp1)
canvas = tk.Canvas(root, height=height*1, width=width*1, bg="black")
canvas.create_image(width*1/2, height*1/2, image=image)
canvas.pack()
def SS_Part2():
image_file_ssp2 = "goat2.gif"
image = tk.PhotoImage(file=image_file_ssp2)
canvas = tk.Canvas(root, height=height*1, width=width*1, bg="black")
canvas.create_image(width*1/2, height*1/2, image=image)
canvas.pack()
def SS_Part3():
image_file_ssp3 = "goat3.gif"
image = tk.PhotoImage(file=image_file_ssp3)
canvas = tk.Canvas(root, height=height*1, width=width*1, bg="black")
canvas.create_image(width*1/2, height*1/2, image=image)
canvas.pack()
def SS_Part4():
image_file_ssp4 = "goat4.gif"
image = tk.PhotoImage(file=image_file_ssp4)
canvas = tk.Canvas(root, height=height*1, width=width*1, bg="black")
canvas.create_image(width*1/2, height*1/2, image=image)
canvas.pack()
def SS_Part5():
image_file_ssp5 = "goat5.gif"
image = tk.PhotoImage(file=image_file_ssp5)
canvas = tk.Canvas(root, height=height*1, width=width*1, bg="black")
canvas.create_image(width*1/2, height*1/2, image=image)
canvas.pack()
def SS_Part6():
image_file_ssp6 = "goat6.gif"
image = tk.PhotoImage(file=image_file_ssp6)
canvas = tk.Canvas(root, height=height*1, width=width*1, bg="black")
canvas.create_image(width*1/2, height*1/2, image=image)
canvas.pack()
t_end = time.time() + 10
while time.time() < t_end:
SS_Part1()
time.sleep(0.05)
SS_Part2()
time.sleep(0.05)
SS_Part3()
time.sleep(0.05)
SS_Part4()
time.sleep(0.05)
SS_Part5()
time.sleep(0.05)
SS_Part6()
root.mainloop()
These are some changes in your code, It should work properly.
import tkinter as tk
from itertools import cycle
# foreign library, need to installed
from ImageTk import PhotoImage
images = ["first1.jpg", "first2.jpg", "first3.jpg", "first4.jpg"]
photos = cycle(PhotoImage(file=image) for image in images)
def slideShow():
img = next(photos)
displayCanvas.config(image=img)
root.after(50, slideShow) # 0.05 seconds
root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenwidth()
root.geometry('%dx%d' % (640, 480))
displayCanvas = tk.Label(root)
displayCanvas.pack()
root.after(10, lambda: slideShow())
root.mainloop()
This is the Object-Oriented version of the above code, Recommended. Below code will work perfectly for the full screen slideshow
from itertools import cycle
import tkinter as tk
# foreign library, need to installed
from ImageTk import PhotoImage
images = [ "first1.jpg", "first2.jpg", "first3.jpg", "first4.jpg"]
class Imagewindow(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.photos = cycle(
PhotoImage(file=image) for image in images
)
self.displayCanvas = tk.Label(self)
self.displayCanvas.pack()
def slideShow(self):
img = next(self.photos)
self.displayCanvas.config(image=img)
self.after(50, self.slideShow) # 0.05 seconds
def run(self):
self.mainloop()
root = Imagewindow()
width = root.winfo_screenwidth()
height = root.winfo_screenwidth()
root.overrideredirect(True)
root.geometry('%dx%d' % (width*1, height*1))
root.slideShow()
root.run()