I have an application wherein, I have to pop a Spinbox widget on click of a button. The widget needs to be overlayed on a background which is an image. I have tried with the code below, but the widget does not appear on the click of the button. I believe the image display is taking precedence over the widget display.
import tkinter as tk
import cv2
from PIL import Image,ImageTk
top = tk.Tk()
count = 1
image = cv2.imread("frames/0.jpg")
w = tk.Spinbox(top, from_=0, to=10)
def helloCallBack():
global count,w
if count%2 != 0:
w.pack()
else:
w.forget()
print(count)
count+=1
B = tk.Button(top, text ="Hello", command = helloCallBack)
B.pack()
label = tk.Label(top)
label.pack()
img = Image.fromarray(image)
imgtk = ImageTk.PhotoImage(image=img)
label.imgtk = imgtk
label.configure(image=imgtk)
top.update()
top.mainloop()
I do not know if this is effect you are looking for:
I used place() and place_forget() to achieve that:
import tkinter as tk
import cv2
from PIL import Image,ImageTk
top = tk.Tk()
count = 1
def helloCallBack():
global count,w
if count%2 != 0:
w.place(x=180, y=650)
else:
w.place_forget()
print(count)
count+=1
B = tk.Button(top, text ="Hello", command = helloCallBack)
B.pack()
label = tk.Label(top)
label.pack()
image = cv2.imread("frames/0.jpg")
img = Image.fromarray(image)
imgtk = ImageTk.PhotoImage(image=img)
label.imgtk = imgtk
label.configure(image=imgtk)
w = tk.Spinbox(top, from_=0, to=10)
top.update()
top.mainloop()
Related
I'm trying to add a capture image on a previewed webcam on second window, for more functional GUI it seems I cant put the capture function, I had no idea Whats going.
here is my code:
from asyncio import wait_for
from enum import auto
from pathlib import PosixPath
from time import sleep
from tkinter import *
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import messagebox
import os
import cv2
from PIL import Image, ImageTk
import datetime
#GLOBALS
font_size = 14
###instantiate videocapture
##cap = cv2.VideoCapture(0)
### Check if the webcam is opened correctly
##if not cap.isOpened():
## raise IOError("Cannot open webcam")
def browsefunc(ent):
filename = askopenfilename(filetypes=([
("image", ".jpeg"),
("image", ".png"),
("image", ".jpg"),
]))
ent.delete(0, tk.END)
ent.insert(tk.END, filename) # add this
label_result1.config(text = "")
def show_frames():
# Get the latest frame and convert into Image
direct_img = cap.read()[1]
cv2image= cv2.cvtColor(direct_img,cv2.COLOR_BGR2RGB)
img = Image.fromarray(cv2image)
# Convert image to PhotoImage
imgtk = ImageTk.PhotoImage(image = img)
label_cam.imgtk = imgtk
label_cam.configure(image=imgtk,height=300)
# Repeat after an interval to capture continiously
label_cam.after(20, show_frames)
return
#function to capture image on camera
#ADD THE FULL PATH if you want a separate location
#for example C:\Images\
def captureImage():
image1_path_entry.delete(0, tk.END)
image_to_write = cap.read()[1]
x=datetime.datetime.now()
## filetowrite = "c"+x.strftime("%m%d%Y%H%M%S")+".jpeg"
filetowrite = "c.jpeg"
print(str(filetowrite))
cv2.imwrite(str(filetowrite),image_to_write)
image1_path_entry.insert(0,filetowrite)
return
root = tk.Tk()
root.title("Signature verification")
def preview(path1):
# Toplevel object which will
# be treated as a new window
newWindow = Toplevel(root)
# sets the title of the
# Toplevel widget
newWindow.title("Preview")
# sets the geometry of toplevel
newWindow.geometry("500x500")
def closeit():
newWindow.destroy()
return 0
image = Image.open(path1)
width = 180
height = 170
resize_image = image.resize((width, height))
img = ImageTk.PhotoImage(resize_image)
panel = Label(newWindow, image = img)
panel.image =img
panel.pack()
# A Label widget to show in toplevel
button1 = Button(newWindow, text="Close", command = closeit)
button1.pack()
def camera(path1):
# Toplevel object which will
# be treated as a new window
newWindow = Toplevel(root)
# sets the title of the
# Toplevel widget
newWindow.title("Camera")
# sets the geometry of toplevel
newWindow.geometry("500x500")
def closeit():
newWindow.destroy()
return 0
show_frames()
takePicture_button = tk.Button(
frame_buttons, text="Capture Signature", font=font_size,command=lambda: captureImage())
takePicture_button.pack(fill=X,ipadx=5,ipady=5,pady=2)
button1 = Button(newWindow, text="Close", command = capture)
button1.pack()
# specify resolution or size of window
#Waveshare 5" inch LCD (G) is 800 x 480, just check to be sure
#https://www.waveshare.com/wiki/5inch_HDMI_LCD_(G)
window_width = 400
window_height = 500
# get the screen dimension
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# find the center point
center_x = int(screen_width/2 - window_width / 2)
center_y = int(screen_height/2 - window_height / 2)
# set the position of the window to the center of the screen
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
# prevent window resizing
root.resizable(False,False)
# this is the placeholder for the camera
frame_cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
frame_cam = tk.Frame(root, height=300, bg="blue")
frame_cam.pack(fill=X)
label_cam = tk.Label(frame_cam,bg="violet")
label_cam.pack()
# frame to hold the signature label and text entry
frame_dirpath = tk.Frame(root)
frame_dirpath.pack(fill=X,ipadx=5,ipady=5)
image1_path_entry = tk.Entry(frame_dirpath, font=font_size,width=25)
image1_path_entry.pack(side=RIGHT,expand=True, ipadx=5,ipady=5)
# frame to hold the buttons and results
frame_buttons = tk.Frame(root)
frame_buttons.pack(fill=BOTH,ipadx=5,ipady=5)
img1_browse_button = tk.Button(
frame_buttons, text="Browse", font=font_size, command=lambda: browsefunc(ent=image1_path_entry))
img1_browse_button.pack(fill=X,ipadx=5,ipady=5,pady=5)
preview_button = tk.Button(
frame_buttons, text="Preview",fg = "green", border = "4",font="Aria 14 bold", command=lambda: preview(
path1=image1_path_entry.get()))
preview_button.pack(fill=X,ipadx=5,ipady=5,pady=5)
camera_btn = tk.Button(
frame_buttons, text="CAMERA",fg = "green", border = "4",font="Aria 14 bold", command=lambda: preview(
path1=image1_path_entry.get()))
camera_btn.pack(fill=X,ipadx=5,ipady=5,pady=5)
root.mainloop()
I get no response on the second window for the camera view, i tried calling the outside function to the new window theres no error but no response
I have just started utilizing Python's tkinter module to create some basic GUIs. In the GUI shown below, the user is prompted to upload the cafe image and subsequent cafe name will appear. However, I have not found a convenient way to clear the cafe label text for when the user upload another cafe image and classify again. I have the full code attached below.
import numpy as np
import cv2
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import ImageTk, Image
from h5py import File
def upload():
global img
global filename
f_types = [('Png files', '*.png')]
filename = filedialog.askopenfilename(filetype=f_types)
img = ImageTk.PhotoImage(file = filename)
e1 = tk.Label(window)
e1.place(x=50, y=150)
e1['image'] = img
window.configure(background = '#CDCDCD')
show_classify_button()
def show_classify_button():
classify_btn = tk.Button(window, text='Classify Image', command=classification)
classify_btn.place(x=250, y=400)
classify_btn.configure(background = '#364156', foreground = 'white', font=('cambria', 15, 'bold') )
def classification():
matrix = []
image = cv2.imread(filename, 0)
array = np.array(image)
flatten_array = array.flatten()
matrix.append(flatten_array)
X = pca.transform(matrix)
pred = clf.predict(X)
if pred == 0:
Label(window, text='Casa De Cafe', font='Cambria 20 bold', background = '#CDCDCD', foreground = '#364156').place(x=170, y=300)
elif pred == 1:
Label(window, text='Coffeology', font='Cambria 20 bold', background = '#CDCDCD', foreground = '#364156').place(x=170, y=300)
else:
Label(window, text='Mori Cafe', font='Cambria 20 bold', background = '#CDCDCD', foreground = '#364156').place(x=170, y=300)
def main_account_screen():
global window
window = Tk()
window.title('Cafe Recognition System')
window.geometry('500x500')
window.configure(background = '#CDCDCD')
Label(window, text='Cafe Recognition System', font='Cambria 20 bold', background = '#CDCDCD', foreground = '#364156').place(x=110, y=50)
button = tk.Button(window, text='Upload', command=upload)
button.place(x=130, y=400)
button.configure(background = '#364156', foreground = 'white', font=('cambria', 15, 'bold') )
window.mainloop()
main_account_screen()
Good day everyone, can I ask how can I manage to put this button inside an image background
code:
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title("Japanese Retro Hub")
root.geometry('2200x1000')
#Image
bg = Image.open("RetroHub_BG_Main.png")
resized = bg.resize((2200,1000), Image.ANTIALIAS)
bg = ImageTk.PhotoImage(resized)
bglabel = Label(root, image=bg)
bglabel.pack(pady=20)
#text for my_command and Start exit button
text = Label(root, text= "Hello world")
text.pack(pady=30)
def my_command():
text.config(text="You have clicked Me...")
def start_exit_button():
click_btn = PhotoImage(file='start_button.png')
img_label= Label(image=click_btn)
button = Button(root, image=click_btn,command=my_command,borderwidth=0)
button.pack(padx=50, pady=20)
root.mainloop()
start_exit_button()
root.mainloop()
This is the image example that I am trying to portray
https://drive.google.com/file/d/1VzbhNazEnfOCk0_QZOD_nWR5jsb-a8GB/view?usp=sharing
I have program that can show webcam image/video on tkinter. I want my program to run method when I press certain key (from keyboard) or button (tkinter button) inside tkinter. Here is my code:
from tkinter import *
from PIL import Image, ImageTk
import cv2
root = Tk()
label =Label(root)
label.grid(row=0, column=0)
cap= cv2.VideoCapture(0, cv2.CAP_DSHOW)
def show_frames():
cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image = img)
label.imgtk = imgtk
label.configure(image=imgtk)
label.after(20, show_frames)
def method():
print("test")
show_frames()
root.after(2000, method)
root.mainloop()
Problem with this code is was that first it ran only once. Then I tried to change the method it in this:
def method():
while True:
print("test")
Problem with this is that it freezes first the window and ultimately crashes the program. Even with only this one print statement.
how would you suggest I go about this? Or is there other method than after that I should use instead?
I added a key_pressed function and now it handles multiple key presses you can see it yourself on the console.
from tkinter import *
from PIL import Image, ImageTk
import cv2
root = Tk()
label =Label(root)
label.grid(row=0, column=0)
cap= cv2.VideoCapture(0, cv2.CAP_DSHOW)
def show_frames():
cv2image= cv2.cvtColor(cap.read()[1],cv2.COLOR_BGR2RGB)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image = img)
label.imgtk = imgtk
label.configure(image=imgtk)
label.after(20, show_frames)
def key_pressed(event):
method()
def method():
print("test")
show_frames()
root.bind("<Key>", key_pressed)
root.mainloop()
Im trying to set up simple frame work for a trashy hang man game, the images are named in series of 6 for each stage of failure. S0 is the beginning and S6, is the final stage.
Im trying to figure out how to upudate the photo.
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
i=0
frameLeft = Frame(root)
frameRight = Frame(root)
frameRight.pack(side=RIGHT)
frameLeft.pack(side=LEFT)
#frame Left
#function Declaration
entry1 = Entry(frameLeft)
entry1.pack()
def updatePhoto():
i = entry1.get()
img = ImageTk.PhotoImage(Image.open("S" + i + ".gif"))
imgPanel = Label(frameRight, image = img)
imgPanel.pack(side=BOTTOM, fill=BOTH, expand=YES)
labelInstruction = Label(frameLeft, text=entry1.get())
labelInstruction.pack()
submitButton = Button(frameLeft, text="Submit", command=updatePhoto)
submitButton.pack()
#frame Right
img = ImageTk.PhotoImage(Image.open("S" + str(i) + ".gif"))
imgPanel = Label(frameRight, image = img)
imgPanel.pack(side=BOTTOM, fill=BOTH, expand=YES)
root.mainloop()
Instead of these lines:
imgPanel = Label(frameRight, image = img)
imgPanel.pack(side=BOTTOM, fill=BOTH, expand=YES)
I was able to use these
imgPanel.configure(image=img)
imgPanel.image = img
I also changed the order of left and right side making right come first as it's a scripting language and requires declaration.