Nov-27-2019, 07:59 AM
Hi, I am trying to place Image as background in frame which contains the textfield, button, and label.
Mentioned below is my code kindly help me out
Mentioned below is my code kindly help me out
import os
import json
import time
import pyfirmata
import multiprocessing
import serial.tools.list_ports
import tkinter as tk
from tkinter.filedialog import asksaveasfile
from tkinter import messagebox
from PIL import ImageTk, Image
data = ['LH', 'RH']
WAIT_BARCODE = r"images\wait_barcode.jpg"
WRONG_BARCODE = r"images\wrong_barcode.jpg"
Press = r"images\Press.jpg"
Done = r"images\done.jpg"
DATA_PATH = "data"
JSON_PATH = r"json\data.json"
JSON_FOLDER_PATH = "json"
barcode_start = 4
barcode_stop = 10
high_pin = 13
input_pin = 10
NA = "NA"
check = "NA"
def dump_to_json(json_dict, filename):
with open(filename, 'w') as file:
json.dump(json_dict, file)
def read_json(filename):
with open(filename, 'r') as file:
json_dict = json.load(file)
return json_dict
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.ard_stat = read_json(JSON_PATH)
#if self.ard_stat['COM_PORT'] == ['OK']:
self.switch_frame(StartPage)
#else:
#tk.messagebox.showinfo("Info", "Arduino is not connected, Please Try Again!")
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def loopCap(self):
#self.master.geometry("1000x700+%d+%d" % (((self.master.winfo_screenwidth() / 2.) - (1280 / 2.)), ((self.master.winfo_screenheight() / 2.) - (720/ 2.))))
#self.master.state('zoomed')
# print(data)
with open(JSON_PATH) as json_file1:
self.data = json.load(json_file1)
#print(self.data)
if self.data['status'] == 'ACTIVE': #and (self.data['RH_img']!= 'null' or self.data['LH_img']!= 'null')
a = self.text.set(self.data['status'])
b = self.text1.set(self.data['RH_cnt'])
c = self.text2.set(self.data['LH_cnt'])
d = self.text3.set(self.data['barcode'])
#print(b)
#print(c)
#print(a)
#print(d)
if self.data['RH_img'] == 'NA':
#print(self.data['RH_img'])
self.img = Image.open(Press)
self.img.load()
else:
#print(self.data['RH_img'])
self.img = Image.open(self.data['RH_img'])
self.img.load()
#print("updated Image")
if self.data['RH_cnt'] == 0:
self.img = Image.open(Done)
self.img.load()
#else:
# self.img = Image.open(self.data['RH_img'])
# self.img.load()
if self.data['LH_img'] == 'NA':
#print(self.data['LH_img'])
self.img1 = Image.open(Press)
self.img1.load()
else:
#print(self.data['LH_img'])
self.img1 = Image.open(self.data['LH_img'])
self.img1.load()
#print("updated Image")
if self.data['LH_cnt'] == 0:
self.img1 = Image.open(Done)
self.img1.load()
#else:
# self.img1 = Image.open(self.data['LH_img'])
# self.img1.load()
elif self.data['status']=='NA':
status = self.text.set(self.data['status'])
#resp = tk.messagebox.showinfo("Info", "New Data Detected Please Add Images")
#print(resp)
count_RH = self.text1.set(self.data['RH_cnt'])
count_LH = self.text2.set(self.data['LH_cnt'])
self.text3.set(self.data['barcode'])
#print(count_RH)
#print(count_LH)
self.img = Image.open(WAIT_BARCODE)
self.img1 = Image.open(WAIT_BARCODE)
#print("updated Image")
elif self.data['status'] == 'INACTIVE':
status = self.text.set(self.data['status'])
# resp = tk.messagebox.showinfo("Info", "New Data Detected Please Add Images")
# print(resp)
count_RH = self.text1.set(self.data['RH_cnt'])
count_LH = self.text2.set(self.data['LH_cnt'])
self.text3.set(self.data['barcode'])
# print(count_RH)
# print(count_LH)
self.img = Image.open(WRONG_BARCODE)
self.img1 = Image.open(WRONG_BARCODE)
#self.img = Image.open(text['RH_img'])
self.photo = ImageTk.PhotoImage(self.img)
self.label['image'] = self.photo
#=========2nd Snap==================
#self.img1 = Image.open("img.jpg")
self.photo1 = ImageTk.PhotoImage(self.img1)
self.label1['image'] = self.photo1
#print("updated")
self.master.after(500, self.loopCap)
return self.text, self.text1, self.text2, self.text3, self.data
def next_save(self):
#self.data1 = self.loopCap()
#print("Save The Button")
#print(self.data)
new_string = self.data['barcode'][4:10]
#tk.messagebox.showinfo("Info", "New Data Detected Please Add Images")
#print(new_string)
new_folder = os.path.join(DATA_PATH,new_string)
if os.path.exists(new_folder):
#print("Folder Already Exists If Condition")
tk.messagebox.showinfo("Info", "Folder Already Exists")
else:
#os.isfile(new_string)
#print("Folder Already Exists")
#tkMessageBox.showinfo("Info", "Folder Already Exists")
#print("Make Directory Else Condition")
json_dict = read_json(JSON_PATH)
json_dict.update({"frontend_status": "True"})
dump_to_json(json_dict, JSON_PATH)
os.mkdir(new_folder)
for i in range(0,len(data)):
folder_name = os.path.join(DATA_PATH, new_string, data[i])
os.mkdir(folder_name)
files = [('All Files', '*.*'),
('Python Files', '*.py'),
('Text Document', '*.txt')]
file = asksaveasfile(initialdir=folder_name, filetypes=files, defaultextension=files)
json_dict = read_json(JSON_PATH)
json_dict.update({"frontend_status": "False"})
dump_to_json(json_dict, JSON_PATH)
self.master.after(500, self.loopCap)
def __init__(self, master):
super().__init__(master)
self.master.geometry("1000x700+%d+%d" % (((self.master.winfo_screenwidth() / 2.) - (1280 / 2.)), ((self.master.winfo_screenheight() / 2.) - (720 / 2.))))
#self.master.state('zoomed')
self.master.config(bg='powder blue')
#myvar = self.master
Frame1 = tk.Frame(self.master)
Frame1.pack(side="bottom", fill="x", pady=10, anchor='w')
Frame2 = tk.Frame(self.master)
Frame2.pack(side="left", fill="both", pady=10, anchor='w', expand=True )
photo = tk.PhotoImage(file="images/BG.jpg")
label = tk.Label(Frame2, image=photo)
label.image = photo
label.place(x=0, y=0)
tk.Label(Frame2, text=' Decal Check ', font=('arial', 25, 'bold'), bg='powder blue',
fg='black', anchor='w').grid(column=0,pady=2)
tk.Label(Frame2, text="Status:", bg='powder blue', font=('arial', 12, 'bold')).grid(row=3,column=0, padx=1, sticky='w')
self.text = tk.StringVar()
tk.Label(Frame2, textvariable=self.text, bg='powder blue',font=('arial', 12, 'bold')).grid(row=3,padx=1, column=1, sticky='w')
tk.Label(Frame2, text="RH_COUNT: ", bg='powder blue', font=('arial', 12, 'bold')).grid(row=4,padx=1,column=0, sticky='w')
self.text1 = tk.StringVar()
tk.Label(Frame2, textvariable=self.text1, bg='powder blue',font=('arial', 12, 'bold')).grid(row=4, padx=1, column=1,sticky='w')
tk.Label(Frame2, text=" LH_COUNT: ", bg='powder blue', font=('arial', 12, 'bold')).grid(row=5, padx=1, column=0,sticky='w')
self.text2 = tk.StringVar()
tk.Label(Frame2, textvariable=self.text2, bg='powder blue', font=('arial', 12, 'bold')).grid(row=5, padx=1, column=1, sticky='w')
tk.Label(Frame2, text=" Barcode: ", bg='powder blue', font=('arial', 12, 'bold')).grid(row=6, padx=1, column=0, sticky='w')
self.text3 = tk.StringVar()
tk.Label(Frame2, textvariable=self.text3, bg='powder blue', font=('arial', 12, 'bold')).grid(row=6, padx=1, column=1, sticky='w')
# tk.Label(Frame2, text=" Enter the Barcode: ", bg='powder blue', font=('arial', 12, 'bold')).grid(row=7, padx=1, column=0, sticky='w')
#self.text4 = tk.StringVar()
#tk.Entry(Frame2, font=('arial', 15, 'bold'), textvariable=self.text4).grid(row=7, padx=1, column=1, sticky='w')
#b = tk.Button(Frame2, text="Submit", command=self.submit)
#b.grid(row=7, column=2, pady=5,sticky='w')
self.label = tk.Label(Frame2,bg='powder blue')
self.label.grid(row=8, column=0, padx=5, pady=5, sticky='w')
self.label1 = tk.Label(Frame2, bg='powder blue')
self.label1.grid(row=8, column=1, padx=5, pady=5,sticky='w')
tk.Label(Frame2, text=" RH Image ", bg='powder blue', font=('arial', 12, 'bold')).grid(row=10, padx=1, column=0, sticky='n')
tk.Label(Frame2, text=" LH Image ", bg='powder blue', font=('arial', 12, 'bold')).grid(row=10, padx=1, column=1, sticky='n')
b = tk.Button(Frame2, text="Add New Files", command= self.next_save)
b.grid(row=11, column=1, pady=5, sticky='w')
self.master.after(500, self.loopCap)
def submit(self):
check = (self.text4.get())
#print(check)
return check
def ui_main():
app = SampleApp()
app.mainloop()
def read_com_port():
com_port = "NA"
while True:
ports = list(serial.tools.list_ports.comports())
if ports:
for p in ports:
str2 = str(p)
# print(len(str2), str2)
if "Arduino" in str2:
# print("done", str2)
index1 = str2.find("COM")
index2 = index1 + 5
com_port = str2[index1:index2]
print("Switch found on COM port = ", com_port)
temp_dict = read_json(JSON_PATH)
temp_dict.update({'COM_PORT': 'OK'})
dump_to_json(temp_dict, JSON_PATH)
if com_port == "NA":
print("Could not detect Switch")
else:
print("No device is detected. Please check com ports")
time.sleep(2)
if com_port != "NA":
break
return com_port
def arduino_init():
brd = pyfirmata.Arduino(read_com_port())
brd.digital[high_pin].write(1)
it = pyfirmata.util.Iterator(brd)
it.start()
brd.digital[input_pin].mode = pyfirmata.INPUT
return brd
def find_folder(barcode):
folder_name = ""
flag = False
if os.path.exists(DATA_PATH):
with os.scandir(DATA_PATH) as entries:
for entry in entries:
dir_name = entry.name
for name in dir_name.split(" "):
if barcode[barcode_start:barcode_stop] == name:
folder_name = os.path.join(DATA_PATH, dir_name)
flag = True
break
return folder_name, flag
def init_json_folder():
while True:
if os.path.exists(JSON_FOLDER_PATH):
print("JSON Folder Exists")
if not os.path.exists(JSON_PATH):
print("JSON file does not exist")
json_dict = ({"status": NA, "barcode": NA, "RH_img": NA, "LH_img": NA, "RH_cnt": NA, "LH_cnt": NA, "frontend_status": "False", "COM_PORT": NA})
dump_to_json(json_dict, JSON_PATH)
print("JSON file created")
break
#new_name = input("Enter a new folder name")
#if new_path not in new_name:
# new_path = os.path.join(DATA_PATH, new_name)
# os.mkdir(new_path)
else:
print("JSON folder does not exist.")
os.mkdir(JSON_FOLDER_PATH)
def traverse_folder(folder_path, board):
# print("folder")
frh = folder_path + r"\RH"
flh = folder_path + r"\LH"
while True:
cflag = False
json_dict = read_json(JSON_PATH)
with os.scandir(frh) as entries:
cnt_rh = 0
for entry in entries:
cnt_rh += 1
with os.scandir(flh) as entries:
cnt_lh = 0
for entry in entries:
cnt_lh += 1
temp_list = [cnt_lh, cnt_rh]
loop_cnt = max(temp_list)
for i in range(1, loop_cnt+1):
"""
while True:
choice1 = board.digital[input_pin].read()
time.sleep(.01)
choice2 = board.digital[input_pin].read()
time.sleep(.01)
choice3 = board.digital[input_pin].read()
time.sleep(.01)
choice = choice1 & choice2 & choice3
if choice:
break
"""
choice = input("Press Y to continue")
#choice = StartPage.submit()
if choice == 'Y' or choice == 'y':
#if choice:
if i <= cnt_lh:
lh_file = os.path.join(flh, str(i)+".png")
lh_cnt = i
else:
lh_file = NA
lh_cnt = 0
if i <= cnt_rh:
rh_file = os.path.join(frh, str(i)+".png")
rh_cnt = i
else:
rh_file = NA
rh_cnt = 0
json_dict.update({"status": "ACTIVE", "RH_img": rh_file, "LH_img": lh_file, "RH_cnt": rh_cnt, "LH_cnt": lh_cnt})
dump_to_json(json_dict, JSON_PATH)
print(i, lh_file, rh_file)
time.sleep(1)
if i == loop_cnt:
cflag = True
#choice = input("Press Y to continue")
#if choice == 'Y' or choice == 'y':
"""
while True:
choice1 = board.digital[input_pin].read()
time.sleep(.01)
choice2 = board.digital[input_pin].read()
time.sleep(.01)
choice3 = board.digital[input_pin].read()
time.sleep(.01)
choice = choice1 & choice2 & choice3
if choice:
break
"""
if cflag:
json_dict.update({"status": NA, "barcode": NA, "RH_img": NA, "LH_img": NA, "RH_cnt": NA, "LH_cnt": NA})
dump_to_json(json_dict, JSON_PATH)
break
def main():
temp_dict = read_json(JSON_PATH)
temp_dict.update({'COM_PORT': 'NA'})
dump_to_json(temp_dict, JSON_PATH)
#arduino = arduino_init()
arduino = ""
while True:
json_dict = read_json(JSON_PATH)
# print(json_dict)
time.sleep(1)
# print(json_dict['frontend_status'])
if json_dict['frontend_status'] == "False":
s = input("Enter the barcode: ")
print("You entered the value ", s)
json_dict.update({"status": NA, "barcode": NA, "RH_img": NA, "LH_img": NA, "RH_cnt": NA, "LH_cnt": NA, "frontend_status": "False"})
dump_to_json(json_dict, JSON_PATH)
if s == 'exit':
break
elif s != NA:
folder_path, flag = find_folder(s)
if flag:
print("Active status")
json_dict.update({'status': 'ACTIVE', "barcode": s})
dump_to_json(json_dict, JSON_PATH)
traverse_folder(folder_path, arduino)
else:
print("Inactive status")
json_dict.update({'status': 'INACTIVE', "barcode": s, "RH_img": NA, "LH_img": NA})
dump_to_json(json_dict, JSON_PATH)
else:
print("No barcode entered")
if __name__ == '__main__':
init_json_folder()
p1 = multiprocessing.Process(target=ui_main)
p1.start()
main()
# s="QWEWWHBDGEWQSDQA", 'WQSDWHBDUFFEWSA'
