Tk Window closing not going to classes - python

I've been running my code on python idle while working on this and didn't receive any problems until I tried running it on visual studio. When running it the tk window just closes and it doesn't go to the classes it tells it too. I am still learning so I probably have some mistakes I would love to get any feedback.
import tkinter as tk
#Takes photos with certain char and if clicked another char program stops
from cv2 import *
import numpy as np
import cv2
import os
from datetime import datetime
now = datetime.now()
time = now.strftime("%H:%M:%S")
#sets the directory and text info
os.chdir(r"C:\Users\asdasd\Desktop\camera")
file_name = 'pic'
cam = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_TRIPLEX
org = (00,300)
fontScale = 1
color = (255,0,0)
thickness = 1
root= tk.Tk()
photo = tk.PhotoImage(file=r"C:\Users\asdas\Desktop\camera\pic.png")
root.iconphoto(False, photo)
root.geometry("+0+50")
print("created window")
#Creates window
canvas1 = tk.Canvas(root, width = 600, height = 600)
canvas1.pack()
canvas1.configure(bg='lightgray')
root.title("ShippingData")
root.lift()
#text label for batch #
label1 = tk.Label(root, text='Enter Batch# :')
label1.config(font=('helvetica', 15))
canvas1.create_window(65, 50, window=label1)
print("created window")
#creates input window for batch #
entry1 = tk.Entry (root)
canvas1.create_window(200, 50, window=entry1)
#text label for initials
label1 = tk.Label(root, text='Enter initials :')
label1.config(font=('helvetica', 15))
canvas1.create_window(65, 100, window=label1)
#creates input window for intials
entry2 = tk.Entry (root)
canvas1.create_window(200, 100, window=entry2)
#gets the info after start button is pressed
def getInfo ():
print("getinfo")
x1 = entry1.get()
x2 = entry2.get()
name = str(x1 + x2)
global dirname
dirname = name
os.mkdir(dirname)
label1 = tk.Label(root, text= "Program Starting")
canvas1.create_window(200, 230, window=label1)
canvas1.destroy()
programStarted()
print("button")
button1 = tk.Button(root, text='Start', command=getInfo)
print("button created")
canvas1.create_window(200, 180, window=button1)
print("canvas created for window")
def programStarted():
print("programstart")
root.update()
#creates new window
global canvas2
canvas2 = tk.Canvas(root, width = 400, height = 300)
canvas2.pack()
# Camera instructions
label2 = tk.Label(root, text= "Press z to take Photos.")
canvas2.create_window(200, 100, window=label2)
label3 = tk.Label(root, text= "Press c multiple times when finished to stop taking photos. ")
canvas2.create_window(200, 150, window=label3)
root.update()
camera()
#camera program
def camera():
print("camera")
global n
global time
global path
n= 1
while(True):
numphoto = "#" + str(n)
ret, frame = cam.read()
cv2.namedWindow("Shipping camera", cv2.WINDOW_NORMAL)
scale_percent = 100 # percent of original size
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
scale_percent = 100 # percent of original size
width = int(frame.shape[1] * scale_percent / 100)
height = int(frame.shape[0] * scale_percent / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
cv2.putText(frame, numphoto, org, font, fontScale,color,thickness, cv2.LINE_AA, False)
cv2.imshow('Shipping camera', frame)
cv2.setWindowProperty("Shipping camera", cv2.WND_PROP_TOPMOST, 1)
if cv2.waitKey(1) & 0xFF == ord('z'):
n+=1
cv2.imwrite(os.path.join(dirname,(file_name + (str(n-1)) + ".jpg")), frame)
path = (os.path.join(str(r"C:\Users\sadsads\Desktop\camera"), str(dirname)))
elif (cv2.waitKey(1) & 0xFF == ord('c')):
# stops everything
cam.release()
cv2.destroyAllWindows()
with open((path+r'\timelog.txt'), 'w') as f:
f.write(time+ '\n')
now = datetime.now()
time2 = now.strftime("%H:%M:%S")
f.write(time2+ '\n')
y = 0
if(y == 0):
# destory the other windows
root.quit()
root.destroy()
break
else:
root.mainloop()

Related

DHT22 Temp sensor causing Tkinter GUI to lag

Hi I've been trying to implement a DHT22 temperature and humidity sensor with Tkinter GUI where it updates regularly while using the GUI. This is done on a Raspberry Pi 4 using Python. However, while the numbers are updating correctly, it would cause the GUI freeze momentarily while updating the numbers. I have already tried multithreading, but it unfortunately didn't help. Is there any solution to this problem? Any help is greatly appreciated.
Here's the code:
# Import the required libraries
import RPi.GPIO as GPIO
import spidev
import time
import tkinter
from tkinter import *
import tkinter.font as tkFont
from PIL import ImageTk, Image
# import time
import smbus
import serial
import os
import argparse
import Adafruit_DHT
from threading import Thread
SENSOR = Adafruit_DHT.DHT22
# GPIO4 on the Raspberry Pi
SENSOR_PIN = 4
address = 0b01
ssPin = 8
spi = spidev.SpiDev()
spi.open(0,0)
spi.max_speed_hz = 976000
spi.mode = 0b11
#spi.bit_order = msbfirst
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(ssPin,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)
GPIO.setup(26,GPIO.OUT)
GPIO.output(ssPin,GPIO.LOW)
GPIO.output(22,GPIO.HIGH)
GPIO.output(26,GPIO.HIGH)
class App:
def __init__(self, master):
def SendScaleReading(self):
S = scale.get() #retrieve value from slider
if S>0:
S+=155
print(S)
spi.xfer([address ,S]) #write data to slave address
frame = Frame(master)
frame.pack()
scale = tkinter.Scale(root,from_=0,to=100,length=700,bg='black',fg='#0000FF', highlightthickness = 0, bd = 0, command=SendScaleReading) #set parameters of slider
scale.place(relx=0.75, rely=0.05)
#scale.place(relx = 0, rely = 0) # set position of slider
fontstyle = tkFont.Font(family='Arial', size=50) #initialise font
scale['font'] = fontstyle
def PowerFn():
global powerBool
# print(ledBool)
if powerBool:
#print('went to on button')
powerBtn.config(image=On_BtnImg)
powerBtn.image = On_BtnImg
#print("on button configured")
powerLabel.config(text="POWER: ON", fg='#00FF00')
# communicating with arduino
GPIO.output(26,GPIO.LOW)
else:
#print('went to off button')
powerBtn.config(image=Off_BtnImg)
powerBtn.image = Off_BtnImg
#print("off button configured")
powerLabel.config(text="POWER: OFF", fg='#FF0000')
# communicating with arduino
GPIO.output(26,GPIO.HIGH)
powerBool = not powerBool
def DirectionFn():
global directionBool
# print(cbBool)
if directionBool:
#print('went to CbOn button')
directionBtn.config(image = On_BtnImg)
directionBtn.image = On_BtnImg
#print("CbOn button configured")
directionLabel.config(text="FORWARD", fg='#00FF00')
# communicating with arduino
GPIO.output(22,GPIO.HIGH)
else:
#print('went to CbOff button')
directionBtn.config(image = Off_BtnImg)
directionBtn.image = Off_BtnImg
# print("CbOff button configured")
directionLabel.config(text="REVERSE", fg='#FF0000')
# communicating with arduino
GPIO.output(22,GPIO.LOW)
directionBool = not directionBool
def tempsensor():
while True:
print("bruh moment")
h, t = Adafruit_DHT.read_retry(SENSOR, SENSOR_PIN)
print(t)
print(h)
temp = "%.1F" %t
hum = "%.1f" %h
temperature.set(temp+ " *C")
humidity.set(hum+ " %")
time.sleep(1);
root = Tk()
app = App(root)
root.config(bg='black')
#root.attributes('-zoomed', True)
#root.state('fullscreen')
rootWidth = root.winfo_screenwidth()
rootHeight = root.winfo_screenheight()
root.attributes('-zoomed', True)
# Create mini window
#canvas = Canvas(root, bg='black', highlightbackground='white')
#canvas.place(relx=0.1, rely=0.03, relheight=0.51, relwidth=0.505)
temperature = StringVar()
temperature.set("----"+" *C")
humidity = StringVar()
humidity.set("----"+" %")
#root.after(2000, tempsensor)
h, t = Adafruit_DHT.read_retry(SENSOR, SENSOR_PIN)
On_img = Image.open("/home/pi/Downloads/on.png")
Off_img = Image.open("/home/pi/Downloads/off.png")
# Resize the image using resize() method according to the screen height and width
btnWidth = int(rootWidth / 6.4)
print(btnWidth)
infobtnWidth = int(rootHeight / 10)
print(infobtnWidth)
On_resize_img = On_img.resize((btnWidth, btnWidth))
Off_resize_img = Off_img.resize((btnWidth, btnWidth))
On_BtnImg = ImageTk.PhotoImage(On_resize_img)
Off_BtnImg = ImageTk.PhotoImage(Off_resize_img)
normalWidth = 1920 # Width of monitor screen used to write this code
normalHeight = 1080 # Height of monitor screen used to write this code
percentWidth = rootWidth / (normalWidth / 100)
percentHeight = rootHeight / (normalHeight / 100)
scale = ((percentWidth + percentHeight) / 2) / 100
fontsize = int(14 * scale)
fontsize = 50
fontstyle = tkFont.Font(family='Arial', size=fontsize)
titleFontsize = int(50 * scale)
if titleFontsize < 8:
titleFontsize = 8
TitleFontstyle = tkFont.Font(family="Gothic", size=titleFontsize)
## Labels ##
titleLabel = Label(root, text="MAX5487 DigiPot", font=TitleFontstyle, fg="red", bg="black")
titleLabel.place(relx=0.35, rely=0.05)
powerLabel = Label(root, text="POWER: OFF", font=fontstyle, fg='red', bg='black')
powerLabel.place(relx=0.2, rely=0.65, anchor=N)
directionLabel = Label(root, text="FORWARD", font=fontstyle, fg='#00FF00', bg='black')
directionLabel.place(relx=0.5, rely=0.65 , anchor=N)
powerBool = True
# boolean for led button
powerBtn = Button(root, image=Off_BtnImg, bg='black', bd=0, activebackground='black', highlightthickness = 0, command=PowerFn)
powerBtn.place(relx=0.2, rely=0.35, anchor=N)
directionBool = False
directionBtn = Button(root, image=On_BtnImg, bg='black', bd=0, activebackground='black', highlightthickness = 0, command=DirectionFn)
directionBtn.place(relx=0.5, rely=0.35, anchor=N)
templabel = Label(root, textvariable=temperature, font=fontstyle, fg='white', bg='red', highlightthickness = 0)
templabel.place(relx=0.2, rely=0.8, anchor=N)
humidlabel = Label(root, textvariable=humidity, font=fontstyle, fg='white', bg='red', highlightthickness = 0)
humidlabel.place(relx=0.5, rely=0.8, anchor=N)
# Button for closing
exit_button = Button(root, text="Exit", font=fontstyle, fg='white', bg='red', highlightthickness = 0, command=root.destroy)
exit_button.place(relx=0.5, rely=0.9, anchor=N)
background_thread = Thread(target=tempsensor)
background_thread.start()
root.mainloop()

What is the best way to Importing a list from a python function into tkinter GUI

I have the below python script that is running and returning some lists:
How I can trigger an action in the GUI (the second code) using the output of the python script(the first code) is there a general way to do that
I'm using Pycharm as a code editor and I run the scripts using Pycharm builtin functions
import cv2
import time
import os
import HandTrackingModule as htm
def fcf():
wCam, hCam = 640, 480
cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, hCam)
folderPath = "FingerImages"
myList = os.listdir(folderPath)
#print(myList)
overlayList = []
for imPath in myList:
image = cv2.imread(f'{folderPath}/{imPath}')
# print(f'{folderPath}/{imPath}')
overlayList.append(image)
#print(len(overlayList))
pTime = 0
detector = htm.handDetector(detectionCon=0.75)
tipIds = [4, 8, 12, 16, 20]
while True:
success, img = cap.read()
img = detector.findHands(img)
lmList = detector.findPosition(img, draw=False)
ts = time.time()
#print(lmList)
if len(lmList) != 0:
fingers = []
satisfied = []
neutral = []
unsatisfied = []
# Thumb
if lmList[tipIds[0]][1] > lmList[tipIds[0] - 1][1]:
fingers.append(1)
else:
fingers.append(0)
# 4 Fingers
for id in range(1, 5):
if lmList[tipIds[id]][2] < lmList[tipIds[id] - 2][2]:
fingers.append(1)
else:
fingers.append(0)
#print(fingers)
totalFingers = fingers.count(1)
#print(totalFingers)
#h, w, c = overlayList[totalFingers - 1].shape
#img[0:h, 0:w] = overlayList[totalFingers - 1]
#cv2.rectangle(img, (20, 225), (170, 425), (0, 255, 0), cv2.FILLED)
#cv2.putText(img, str(totalFingers), (45, 375), cv2.FONT_HERSHEY_PLAIN,
# 10, (255, 0, 0), 25)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, f'FPS: {int(fps)}', (400, 70), cv2.FONT_HERSHEY_PLAIN,
3, (255, 0, 0), 3)
cv2.imshow("Image", img)
cv2.waitKey(1)
if __name__=='main':
fcf()
and I have the below tkinter GUI:
from tkinter import *
from PIL import ImageTk, Image
from FingerCounter import *
root = Tk()
root.title('Customer Satisfaction Survey')
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
#root.geometry(f'{screen_width}x{screen_height}')
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
root.columnconfigure(2, weight=1)
#root.attributes('-fullscreen',True)
frame = Frame(root)
# Define the images
Img = ImageTk.PhotoImage(Image.open("coo.png"))
Img1 = ImageTk.PhotoImage(Image.open("Doo.png"))
Img2 = ImageTk.PhotoImage( Image.open("Wave.png"))
#
ImgLabel00 = Label(root, text=" \n \n \n \n\n\n\n\n\n\n\n \n \n \n \n ")
ImgLabel00.grid(row=0, column=0, padx=5, pady=5)
ImgLabel = Label(image=Img)
ImgLabel.grid(row=1, column=2, padx=5, pady=5)
ImgLabel1 = Label(image=Img1)
ImgLabel1.grid(row=1, column=0, padx=5, pady=5)
ImgLabel2 = Label(image=Img2)
ImgLabel2.grid(row=1, column=1, padx=5, pady=5)
# craeting a label widget
myLabel = Label(root, text=" ", font=("Arial", 35))
#myLabel1 = Label(root, text=" ")
myLabel2 = Label(root, text=" ", font=("Arial", 35))
#myLabel3 = Label(root, text=" ")
myLabel4 = Label(root, text=" ", font=("Arial", 35))
#shoving it into the screen
myLabel.grid(row=2, column=0)
#myLabel1.grid(row=0, column=2)
myLabel2.grid(row=2, column=1)
#myLabel3.grid(row=0, column=6)
myLabel4.grid(row=2, column=2)
root.mainloop()
I'm not sure if my approach is optimum but this is how I worked it:
I adopted multithreading and created two threads one that is running the Tkinter GUI and the second thread runs the python script.
The python script writes the output of one function to a text file while the GUI on the first thread reads the same text file and triggers the action.

Editing image the edited part of image remain unchanged

Everyone. I want to ask a question. How to make the edited photo able to change with cv2.trackbar (the bug is the trackbar currently doesn't change the edited photo)?
Here's the full code which I created
import tkinter as tk
from PIL import Image as PILImage
from PIL import ImageTk
from tkinter import Label
from tkinter import filedialog
from tkinter import ttk
from tkinter import Menu
import cv2
import matplotlib.pyplot as plt
import numpy as np
effectoption = ["Effect RGB",
"Effect HSV",
"Effect LAB",
"Effect RGBA", "Effect HLS"]
effectoption2 = ["Original(RGB)",
"Original(HSV)",
"Effect3"]
global image, edited
def insertbutton_cb():
global orima, editima
picpath = filedialog.askopenfilename(
title="Select An Image",
filetypes=(("JPG Files", "*.jpg"), ("GIF Files", "*.gif*"), ("PNG files", "*.png"), ("JPEG Files", "*.jpeg"))
)
if len(picpath) > 0:
image = cv2.imread(picpath)
edited = cv2.imread(picpath)
edited = np.array(edited)
#edited = PILImage.fromarray(edited.astype('uint8'))
print(picpath)
print('Original Dimensions : ',image.shape)
print(image)
print(edited)
scale_percent = 50 # percent of original size
width = int(image.shape[1] * scale_percent / 100)
height = int(image.shape[0] * scale_percent / 100)
width2 = int(edited.shape[1] * scale_percent / 100)
height2 = int(edited.shape[0] * scale_percent / 100)
dim = (width, height)
dim2 = (width2, height2)
image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
edited = cv2.resize(edited, dim2, interpolation = cv2.INTER_AREA)
#if effectoption[0] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGB)
#elif effectoption[1] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2HSV)
#elif effectoption[2] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2LAB)
#elif effectoption[3] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGBA)
#elif effectoption[4] :
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2HLS)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGBA)
image = PILImage.fromarray(image)
edited = PILImage.fromarray(edited)
#xa, ya, za = np.shape(image)
#xb, yb, zb = np.shape(edited)
#image = np.ones((xa, ya, za), np.uint8)
#edited = np.ones((xb, yb, zb), np.uint8)
image = np.uint8(image)
edited = np.uint8(edited)
#hueSlider = tk.Scale(Frm2, label="Hue",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=huecb)
#hueSlider.pack(anchor=tk.N)
#saturationSlider = tk.Scale(Frm2, label="Saturation",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=satcb)
#saturationSlider.pack(anchor=tk.N)
#brightSlider = tk.Scale(Frm2, label="Brightness",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=brightcb)
#brightSlider.pack(anchor=tk.N)
#contrastSlider = tk.Scale(Frm2, label="Contrast",from_=0, to=100, orient=tk.HORIZONTAL, length=sw, resolution=1, command=contrastcb)
#contrastSlider.pack(anchor=tk.N)
bright = 255
contrast = 100
saturation = 50
cv2.namedWindow('CV2 Photo Editor')
cv2.createTrackbar('Bright', 'CV2 Photo Editor', 255, 2 * 255, bccb)
cv2.createTrackbar('Contrast', 'CV2 Photo Editor', 255, 2 * 127, bccb)
cv2.createTrackbar('Saturation', 'CV2 Photo Editor', 255, 2 * 255, bccb)
functionbcs(edited, 0, 0, 0)
bccb(0, 0, 0)
teste = controller(edited, bright, contrast, saturation)
cv2.imshow('CV2 Photo Editor', teste)
#cv2.waitKey(0)
if orima is None or editima is None:
orima = Label(image=image)
orima.image = image
orima.pack(side="left", padx= 0, pady=0)
editima = Label(image=edited)
editima.image = edited
editima.pack(side="right", padx= 0, pady=0)
else:
orima.configure(image=image)
editima.configure(image=edited)
orima.image = image
editima.image = edited
def resetbutton_cb():
orima = None
editima = None
def savebutton_cb():
pass
def functionbcs(edited, bright=0, contrast=0, saturation=0):
#edited = cv2.cvtColor(edited, cv2.COLOR_BGR2RGB)
bright = cv2.getTrackbarPos('Bright','CV2 Photo Editor')
contrast = cv2.getTrackbarPos('Contrast','CV2 Photo Editor')
saturation = cv2.getTrackbarPos('Saturation','CV2 Photo Editor')
edited = controller(edited, bright, contrast, saturation)
#print("Edited : " + edited)
print(edited)
cv2.imshow("Edited", edited)
def satcb(satpos = 0):
print(satpos)
def bccb(bright = 0, contrast=0, saturation=0):
print("B : " + str(bright))
bright = cv2.getTrackbarPos('Bright', 'CV2 Photo Editor')
print("C :" + str(contrast))
contrast = cv2.getTrackbarPos('Contrast', 'CV2 Photo Editor')
print("S :" + str(saturation))
saturation = cv2.getTrackbarPos('Saturation', 'CV2 Photo Editor')
def controller(effect, bright=1, contrast=1, saturation=1):
bright = int((bright - 0) * (255 - (-255)) / (510 - 0) + (-255))
contrast = int((contrast - 0) * (127 - (-127)) / (254 - 0) + (-127))
saturation = int((saturation - 0) * (100 - (-100)) / (200 - 0) + (-100))
if bright != 0:
if bright > 0:
shadow = bright
max = 255
else:
shadow = 0
max = 255 + bright
alf = (max - shadow) / 255
gam = shadow
cal = cv2.addWeighted(edited, alfa,
edited, 0, gam)
else:
cal = effect
if contrast != 0:
Alf2 = float(131 * (contrast + 127)) / (127 * (131 - contrast))
Gam2 = 127 * (1 - Alf2)
# The function addWeighted calculates
# the weighted sum of two arrays
cal = cv2.addWeighted(cal, Alf2,
cal, 0, Gam2)
cv2.putText(cal, 'B:{},C:{}, S:{}'.format(bright,
contrast, saturation), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
cv2.imshow('CV2 Photo Editor', effect)
return cal
def exitbutton_cb():
window.destroy()
cv2.destroyAllWindows()
window = tk.Tk()
window.title('Simple Photo Editing')
mb = Menu(window)
#file manager
fm = Menu(mb, tearoff=0)
fm.add_command(label="Open", command=insertbutton_cb)
fm.add_command(label="Save", command=savebutton_cb)
fm.add_separator()
#fm.add_command(label="Cancel Edit", command=pass)
fm.add_command(label="Exit", command=exitbutton_cb)
mb.add_cascade(label="File", menu=fm)
var1 = tk.StringVar(window)
var1.set(effectoption[0])
cr = ttk.Frame(window)
canvas = tk.Canvas(cr)
scrolling = ttk.Scrollbar(cr, orient="vertical", command=canvas.yview)
sw = window.winfo_screenwidth()
sh = window.winfo_screenheight()
Frm = tk.Frame(window, height=50, width=300)
Frm.pack(anchor=tk.N)
Frm2 = tk.Frame(window, height=25, width=100)
Frm2.pack(anchor=tk.NW)
#Frm3 = tk.Frame(window, height=50, width=500)
#Frm3.pack(anchor=tk.N)
#showWin = tk.Label(window, width=100, height=100)
#showWin.pack(side='left')
#showWin2 = tk.Label(window, width=100, height=100)
#showWin2.pack(side='left')
label = ttk.Label(
window, text="Simple Image Photo Editing"
)
resetbutton = tk.Button(Frm, text="Reset", padx=0, pady=0, command=resetbutton_cb)
resetbutton.grid(row=0, column=1)
savebutton = tk.Button(Frm, text="Save", padx=0, pady=0, command=savebutton_cb)
savebutton.grid(row=0, column=2)
orima = None
editima = None
opt = tk.OptionMenu(window, var1, *effectoption)
opt.config(width=90, font=('Helvetica', 12))
opt.pack(side="top")
print(opt)
window.config(menu=mb)
cv2.waitKey(0)
tk.mainloop()
When I tried to apply the photo with cv2 slider, the edited image remain unchanged and the value despite the trackbar can slide normally but still won't change for the photo

how to cancel a timer or stop if i close the app

Im trying to do a selector to run diferent configs on a emulator, and i put a timer to close this app and run the default option.
My problem is when i run the app and close it without a choise the timer continue and dont stop and after the time end run the other app.
import os
import threading
#import shutil
import tkinter as tk
from tkinter import *
def drivers(driver1, driver2):
wait_time.cancel()
ra_config = open("F:\\Games\\RetroArch\\retroarch.cfg", "rt")
temp_data = ra_config.read()
temp_data = temp_data.replace('video_driver = "' + driver1 + '"', 'video_driver = "' + driver2 + '"')
ra_config.close()
ra_config = open("F:\\Games\\RetroArch\\retroarch.cfg", "wt")
ra_config.write(temp_data)
ra_config.close()
os.startfile (r"F:\\Games\\RetroArch\\retroarch.exe")
root.quit()
HEIGHT = 200
WIDTH = 700
root = tk.Tk()
root.title("Choose one")
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x_coordinate = (screen_width/2) - (WIDTH/2)
y_coordinate = (screen_height/2) - (HEIGHT/2)
root.geometry ("%dx%d+%d+%d" % (WIDTH, HEIGHT, x_coordinate, y_coordinate))
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
photo_vul = PhotoImage(file = r"img\\vulkan.png")
photo_gl = PhotoImage(file = r"img\\opengl.png")
photo_icon = PhotoImage(file = r"img\\retroarch-icon.png")
root.iconphoto(False, photo_icon)
#frame = tk.Frame(root, highlightbackground='black', highlightthickness=1, bd=10)
frame = tk.Frame(root, bd=10)
frame.place(relx = 0.5, rely=0.5, relwidth=0.95, relheight=0.95, anchor="c")
button = tk.Button(frame, bg='white', activebackground='white', image = photo_vul, font=60, command=lambda: drivers("glcore", "vulkan"))
button.place(relx = 0.05, relwidth=0.4, relheight=1)
button2 = tk.Button(frame, bg='#0277bd', activebackground='#0277bd', image = photo_gl, font=60, command=lambda: drivers("vulkan", "glcore"))
button2.place(relx = 0.55, relwidth=0.4, relheight=1)
#create the vulkan config if the orig
#og = r"F:\\Games\\RetroArch\\retroarch.cfg"
#tg = r"F:\\Games\\RetroArch\\retroarch-vulkan.cfg"
#shutil.copyfile(og, tg)
#pyinstaller --noconsole --onefile RApicker.py
wait_time = threading.Timer(15.0, drivers,["vulkan", "glcore"]).start()
root.mainloop()
On window delete
def delete_window():
# Stop timer here
root.protocol("WM_DELETE_WINDOW", delete_window)
root.mainloop()
On destroy
def destroy():
# Stop timer here
root.bind("<Destroy>", destroy)
root.mainloop()

How can i change image periodically and label values too

I've 2 questions on your code of changing an image periodically. I've run your code and the images are changing perfectly fine, but when im trying to include your patch with mine the images isn't in order and random images are generating. my code is about web-socket program where the rpi is the client and esp32 is the server and the data is coming in sprintf format.
The thing is that I've to take that data and paste on the images I've in my dir.
there are 4 images and each image has 4 different parameters.
My 2nd question is that when the image is change the data should also get change periodically. also can i set the timings of an image like which image should get display first and its data too.
It'd be a great help if you can enlighten me on this.
i'm putting my code below for your reference.
CODE :
import tkinter as Tk
import tkinter as tk
from tkinter import *
import websocket
from PIL import Image, ImageTk
from parse import *
import image
import itertools
import os
import sys
import shutil
import threading
import time
def update_image(dst):
test_image = '/home/pi/Desktop/kvar pix exb/KVAR PIX P1.jpg', '/home/pi/Desktop/kvar pix exb/KVAR PIX P2.jpg', '/home/pi/Desktop/kvar pix exb/KVAR PIX P3.jpg','/home/pi/Desktop/kvar pix exb/KVAR PIX P4.jpg'
for src in itertools.cycle(test_image):
shutil.copy(src, dst)
time.sleep(1) # pause between updates
def refresh_image(canvas,img,image_path,image_id):
try:
pil_img = Image.open(image_path).resize((width_value,height_value), Image.ANTIALIAS)
img = ImageTk.PhotoImage(pil_img)
canvas.itemconfigure(image_id,image=img)
except IOError:
img = None
#repeat every half sec
canvas.after(500,refresh_image,canvas,img,image_path,image_id)
window = tk.Tk()
image_path = 'test.png'
#comparing the incoming data and addr given by the server
comparing_data = ['\x02','45']
#getting values from server
labeltxt_1 = StringVar()
labeltxt_2 = StringVar()
labeltxt_3 = StringVar()
labeltxt_4 = StringVar()
labeltxt_5 = StringVar()
labeltxt_6 = StringVar()
labeltxt_7 = StringVar()
def comm_loop():
global result,labeltxt_1
ws = websocket.WebSocket()
ws.connect("ws://192.168.4.1:7/")
while 1:
result = ws.recv()
incoming_data = result.split(',')
while 1:
if (incoming_data[1] != comparing_data[1]):
print("unauthorised server")
else:
break
print(incoming_data)
labeltxt_1.set(' '+incoming_data[2])
labeltxt_2.set(' '+incoming_data[3])
labeltxt_3.set(' '+incoming_data[4])
labeltxt_4.set(' '+incoming_data[5])
labeltxt_5.set(' '+incoming_data[6])
labeltxt_6.set(' '+incoming_data[7])
labeltxt_7.set(' '+incoming_data[8])
ws.close()
#threading
thread = threading.Thread(target=comm_loop)
thread.daemon = True
thread.start()
#threading
th = threading.Thread(target = update_image, args=(image_path,))
th.daemon = True
th.start()
while not os.path.exists(image_path):
time.sleep(0.1)
width_value = window.winfo_screenwidth()
height_value = window.winfo_screenheight()
window.attributes("-fullscreen", True)
window.config(highlightthickness = 0)
canvas = Canvas(window,width=1920,height=1080)
label_1 = Label(window, textvariable = labeltxt_1, fg = "#FF8000", font = ("Times",78), bg = "#FFFFFF").place(x = 600, y = 355)
label_2 = Label(window, textvariable = labeltxt_2, fg = "#FF8000", font = ("Times",78), bg = "#FFFFFF").place(x = 640, y = 530)
label_3 = Label(window, textvariable = labeltxt_3, fg = "#FF8000", font = ("Times",78), bg = "#FFFFFF").place(x = 850, y = 710)
label_4 = Label(window, textvariable = labeltxt_4, fg = "#FF8000", font = ("Times",78), bg = "#FFFFFF").place(x = 730, y = 880)
for i in range(0,0.5):
i=i+1
label_5 = Label(window, textvariable = labeltxt_5, fg = "#FF8000", font = ("Times",78), bg = "#FFFFFF").place(x = 600, y = 355)
label_6 = Label(window, textvariable = labeltxt_6, fg = "#FF8000", font = ("Times",78), bg = "#FFFFFF").place(x = 640, y = 530)
label_7 = Label(window, textvariable = labeltxt_7, fg = "#FF8000", font = ("Times",78), bg = "#FFFFFF").place(x = 850, y = 710)
img = None
image_id = canvas.create_image(0,0,anchor=NW,image=img)
canvas.pack()
refresh_image(canvas,img,image_path,image_id)
window.mainloop()

Categories