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()
Related
I have 2 files where I want to put a list of images from my database into my tkinter notebook tab upon searching through my database. However I am unable to do so as when I execute the search button , my tab which the images and details should be populated into still it remains empty. In addition, the details are only shown when I closed the initial application in which a second application will then open to show the details. However what I want is for the details to be populated straightaway into my tkinter notebook tab. Can I ask for some guidance on how I should amend my code?
from cProfile import label
from tkinter import *
from PIL import ImageTk, Image
from tkinter import ttk
root = Tk()
root.geometry("1300x600")
my_tabs = ttk.Notebook(root)
my_tabs.pack()
# style = ttk.Style()
# style.layout("TNotebook.Tab", [])
def back():
my_tabs.select(0)
def back1():
my_tabs.select(1)
def back2():
my_tabs.select(2)
def whenClicked():
global entry
entry = enTree.get()
print(entry,type(entry))
my_tabs.select(1)
my_frame = Frame(my_tabs, width=1300, height=600)
my_frame2 = Frame(my_tabs, width=1300, height=600)
my_frame3 = Frame(my_tabs, width= 1300, height=600)
my_frame4 = Frame(my_tabs, width= 1300, height=600)
my_frame5 = Frame(my_tabs, width= 1300, height=600)
my_frame6 = Frame(my_tabs, width= 1300, height=600)
my_frame.pack(fill="both", expand=1)
my_frame2.pack(fill="both", expand=1)
my_frame3.pack(fill="both", expand=1)
my_frame4.pack(fill="both", expand=1)
my_frame5.pack(fill="both", expand=1)
my_frame6.pack(fill="both", expand=1)
my_tabs.add(my_frame, text="1st tab")
my_tabs.add(my_frame2, text="2nd tab")
my_tabs.add(my_frame3, text="3rd tab")
my_tabs.add(my_frame4, text="4th tab")
my_tabs.add(my_frame5, text="5th tab")
my_tabs.add(my_frame6, text="6th tab")
img = (Image.open("Iphone.jfif"))
resizedImage = img.resize((300, 300), Image.ANTIALIAS)
img2 = ImageTk.PhotoImage(resizedImage)
img3 = (Image.open("Rating.png"))
resizedImage2 = img3.resize((300, 60), Image.ANTIALIAS)
img4 = ImageTk.PhotoImage(resizedImage2)
img5 = (Image.open("Cheese.png"))
resizeImage3 = img5.resize((80,80), Image.ANTIALIAS)
CheesePic = ImageTk.PhotoImage(resizeImage3)
emptyLabel = Label(my_frame)
emptyLabel.pack(pady=80)
#App name/Label
labelOne = Label(my_frame, text = "Compario", font=("Algerian", 50))
labelOne.pack(padx=10,pady=10, anchor=CENTER)
#Search box
enTree = Entry(my_frame, width=60, font=30)
enTree.pack(padx=10,pady=10, ipady=7, anchor=CENTER)
#Search button
buttonOne = Button(my_frame, text = "Search", font=("Arial", 15), padx=25, pady=6, fg="white", bg="grey", command=whenClicked)
buttonOne.pack(padx=10,pady=10,anchor=CENTER)
backButton = Button(my_frame2, text = "Back", command = back)
backButton.place(relx=0.07, rely=0.1, anchor=CENTER)
root.mainloop()
Here is my second file
from tkinter import *
from PIL import ImageTk, Image
from io import BytesIO
import requests
import sqlite3
import GUI3
root = Tk()
root.geometry("1300x600")
#Database output result from site into GUI
Links = []
PName = []
Price = []
Rating = []
a = []
b = []
c = []
d= []
def fetch_db():
connection = sqlite3.connect("site.db")
cursor = connection.cursor()
cursor.execute("SELECT IMAGE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables = cursor.fetchall()
for row in all_tables[:4]:
Links.append(row)
for lItems in Links:
for lItem in lItems:
continue
a.append(lItem)
cursor.execute("SELECT TITLE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables2 = cursor.fetchall()
for row in all_tables2[:4]:
PName.append(row)
for pdItems in PName:
for pdItem in pdItems:
continue
b.append(pdItem)
cursor.execute("SELECT PRICE FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables3 = cursor.fetchall()
for row in all_tables3[:4]:
Price.append(row)
for pItems in Price:
for pItem in pItems:
continue
c.append(pItem)
cursor.execute("SELECT RATING FROM products WHERE TITLE LIKE ?", ("%" + GUI3.entry + "%",))
all_tables4 = cursor.fetchall()
for row in all_tables4[:4]:
Rating.append(row)
for rItems in Rating:
for rItem in rItems:
continue
d.append(rItem)
connection.close()
fetch_db()
for z in range(0, len(a)):
r = requests.get(str(a[z]))
phoneImage = Image.open(BytesIO(r.content)).resize((160, 160), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(phoneImage)
label = Label(image=photo)
label.image = photo
bigB = str(b[z])
bigC = str(c[z])
bigD = str(d[z])
labelImage = Label(GUI3.my_frame2, text ="Hello Educba Technology Institute")
labelText = Label(GUI3.my_frame2, width=22, text=bigB, bg="white").place(x=10+(z+1)*200, y=190)
labelPrice = Label(GUI3.my_frame2, width=20, text=bigC, bg="white").place(x=20+(z+1)*200, y=220)
labelRating = Label(GUI3.my_frame2, width=20, text=bigD+"/5", bg="white").place(x=20+(z+1)*200, y=250)
z += 1
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()
i am making a sign up page and im trying to store the email the user entered to a text file but it doesnt seem to work it stores ".!toplevel.!entrywrite" instead of user input. i am new to this python and tkinter so i dont really know what to do, the code is a little bit long sorry about that.
Any help will be appreciated. Thank you
from tkinter import*
from PIL import Image, ImageTk
import tkinter as tk
root = Tk()
root.geometry('670x466')
class Goode_brothers:
def __init__(self, parent):
myFrame = Frame(parent)
myFrame.pack()
self.load = Image.open('new-dip-project\\food.jpg')
self.render = ImageTk.PhotoImage(self.load)
self.img = Label(parent, image = self.render)
self.img.place(x = -26, y =0)
self.img_login = PhotoImage(file = 'new-dip-project\\button (3).png')
self.b1 = Button(parent,image = self.img_login,bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b1.place(x = 275, y = 310)
self.img_register = PhotoImage(file = 'new-dip-project\\register.png')
self.b2 = Button(parent,image = self.img_register, command = self.openNewWindow, bd = 0, bg = '#3b353b', activebackground = '#3b353b')
self.b2.place(x = 265, y = 400)
self.canvas = Canvas(parent, width = 400, height = 120)
self.canvas.pack()
self.img4 = ImageTk.PhotoImage(Image.open('new-dip-project\\goode.png'))
self.canvas.create_image(20, 20, anchor=NW, image=self.img4)
self.email = Entry(parent).place(x = 340, y = 180)
self.password = Entry(parent).place(x = 340, y = 250)
self.img_label = PhotoImage(file = 'new-dip-project\\label-image.png')
self.name = Label(parent, image = self.img_label, text = "Email:", bg = '#3c3a3b').place(x = 197,y = 178)
self.img_label_pass = PhotoImage(file = 'new-dip-project\\label_pass.png')
self.name = Label(parent, image = self.img_label_pass, text = "Password:", bg = '#3c3a3b').place(x = 177,y = 245)
def create_pass(self):
self.password_length = Label(self.root2, text = '')
self.password_length.place(x = 80, y = 140)
self.pass_word = str(self.password2.get()) #this code is getting the users input from the password entry box
if len(self.pass_word) >= 8: #if the characters gotten from the pasword entry is less than 8, an erorr message will appear
self.registered = Label(self.root2, text = 'You have successfully registered, this window will now automatically close', font=("open sans", "8"))
self.registered.place(x = 80, y = 140)
self.root2.after(4000, self.root2.destroy)
else:
self.password_length.configure(text="""Your password must be atleast eight characters long. Please try again""", font=("open sans", "8"))
def save_info(self):
self.email_reg = str(self.email2.get())
print(self.email2)
file = open('emails.txt', 'w')
file.write(str(self.email2))
def create_email(self):
self.username_length = Label(self.root2, text = '', font = '40')
self.username_length.place(x = 165, y = 140)
self.email_reg = str(self.email2.get())
if len(self.email_reg) >= 1: #if user has inputted a letter or number it will allow it to go to the next function
self.save_info()
self.create_pass()
self.username_length.destroy()
else:
self.username_length.configure(text='Please enter your username or password', font=("open sans", "8"))
self.username_length.after(3000, self.username_length.destroy)
def openNewWindow(self):
# Toplevel object which will
# be treated as a new window
self.root2 = Toplevel(root)
# sets the title of the
# Toplevel widget
self.root2.title("New Window")
# sets the geometry of toplevel
self.root2.geometry("500x300")
self.load2 = Image.open('new-dip-project\\registerscreen3.jpg')
self.render2 = ImageTk.PhotoImage(self.load2)
self.img2 = Label(self.root2, image = self.render2)
self.img2.place(x = -2, y =0)
self.img_label2 = PhotoImage(file = 'new-dip-project\\label-image.png')
self.name = Label(self.root2, image = self.img_label, bg = '#292929').place(x = 130,y = 102)
self.img_label_pass2 = PhotoImage(file = 'new-dip-project\\label_pass.png')
self.name = Label(self.root2, image = self.img_label_pass, bg = '#292929').place(x = 120,y = 173)
self.email2 = Entry(self.root2)
self.email2.place(x = 280, y = 104)
self.password2 = Entry(self.root2)
self.password2.place(x = 280, y = 180)
self.img_register2 = PhotoImage(file = 'new-dip-project\\register.png')
self.b3 = Button(self.root2,image = self.img_register2, command = self.create_email, bd = 0, bg = '#0d0d0d', activebackground = '#0d0d0d')
self.b3.place(x = 180, y = 250)
self.img_reg2 = PhotoImage(file = 'new-dip-project\\regtitle.png')
self.name9 = Label(self.root2, image = self.img_reg2, bg = '#131313')
self.name9.place(x = 109, y = 10)
if __name__ == "__main__":
e = Goode_brothers(root)
root.title('Goode brothers')
root.mainloop()
Using var = StringVar() to set option textvariable - var when initialize Entry, and get content of Entry by var.get().
example Code
from tkinter import *
def on_click():
print(entry_text.get())
root = Tk()
font = ("Courier New", 32)
entry_text = StringVar()
entry = Entry(root, textvariable=entry_text, font=font)
entry.place(x=0, y=0)
button = Button(root, text='Check', command=on_click, font= font)
button.place(x=0, y=64)
root.mainloop()
Following statement will get value None for self.email
self.email = Entry(parent).place(x = 340, y = 180)
should be
self.email = Entry(parent)
self.email.place(x = 340, y = 180)
My program stops working after successfully running the two exes. here is the code:
from tkinter import *
import os
root = Tk()
root.geometry('350x150')
root.title("hurler")
photo = PhotoImage(file = "Logo_Image.png")
root.iconphoto(False, photo)
entry_text = Label(text = "Number of posts you wish to automate (between 1-12) * ")
entry_text.place(x = 15, y = 10)
num = StringVar()
time_entry = Entry(textvariable = num, width = "10")
time_entry.place(x = 15, y = 40)
def action():
global num
num = num.get()
if num == '1':
os.startfile('.\\hurl\\hurl.exe')
# exit()
if num == '2':
os.startfile('.\\hurl\\hurl.exe')
os.startfile('.\\hurl2\\hurl.exe')
# exit()
num = StringVar()
register = Button(root,text = "Make", width = "10", height = "2", command = action, bg = "lightblue")
register.place(x = 15, y = 70)
root.mainloop()
hurl takes in text entries and then runs a web driver exe after pressing the Post button. Heres a sample block from code from hurl:
from tkinter import *
import os
from time import sleep
root = Tk()
root.geometry('600x600')
root.title("hurl")
photo = PhotoImage(file = "Logo_Image.png")
root.iconphoto(False, photo)
def save_post():
emailE = email_in.get()
file1 = open ("user.txt", "w")
file1.write(emailE)
file1.close()
passE = pass_in.get()
file2 = open ('pass.txt', 'w')
file2.write(passE)
file2.close()
entry1_text = Label(text = "Email * ",)
entry2_text = Label(text = "Password * ",)
entry1_text.place(x = 15, y = 70)
entry2_text.place(x = 15, y = 130)
email_in = StringVar()
pass_in = StringVar()
email_entry = Entry(textvariable = email_in, width = "30")
pass_entry = Entry(textvariable = pass_in, width = "30")
def app():
os.system(".\Auto_Post_With_Photo.exe")
def everything():
save_post()
app()
register = Button(root,text = "Post", width = "10", height = "2", command = everything, bg = "lightblue")
register.place(x = 15, y = 380)
root.mainloop()
I'm hoping I don't need to show the last program to get an answer to the issue. The Issue I'm having is that the program runs perfectly until the button is pressed, and then the hurls exes crash.
But if I click on the two hurl.exe with my mouse and not this 3rd program pressing the post button won't crash.
Any ideas to fix this issue? Also, it's not due to the 'exit()s', it does the same thing with or without them. :)
This is my first post and I have googled extensively for an answer but found nothing that works. I'm new to python but have some experience with C++/arduino programming.
I'm trying to make a weather station and display some garage door states as image icons. My issue is when it works, it flickers the images and eventually bogs down the system and runs very slowly. I've tried every combination I can think of making objects global or only changing certain parameters in the Label objects to work around the garbage collection issue I've read about. I've tried Canvas as well, but the issue I had with that is no matter what location coordinates I entered, it always showed up in the top center of the screen.
Edit: as per requested, heres a truncated version:
root = tk.Tk()
global garageOpenIcon
global garageClosedIcon
global doorUnlockedIcon
global doorLockedIcon
global doorOpenIcon
backgroundImage = PhotoImage(file = "background.gif")
garageOpenIcon = PhotoImage(file = "garageOpen.gif")
garageClosedIcon = PhotoImage(file = "garageClosed.gif")
doorLockedIcon = PhotoImage(file = "doorLocked.gif")
doorUnlockedIcon = PhotoImage(file = "doorUnlocked.gif")
doorOpenIcon = PhotoImage(file = "doorOpen.gif")
background = Label(root, image = backgroundImage)
background.place(x = 0, y = 0, relwidth = 1, relheight = 1)
global mainDoorLabel
global sideDoorLabel
mainDoorLabel = Label(root)
sideDoorLabel = Label(root)
def getDoors():
global garageOpenIcon
global garageClosedIcon
global doorOpenIcon
global doorUnlockedIcon
global doorLockedIcon
global mainDoorLabel
global sideDoorLabel
#side door open and unlocked:
if(GPIO.input(sideDoorPin) == GPIO.HIGH):
sideDoorLabel = Label(image = doorOpenIcon)
#closed and unlocked:
elif(GPIO.input(sideDoorPin) == GPIO.LOW):
if(GPIO.input(sideDoorLockPin) == GPIO.HIGH):
sideDoorLabel = Label(image = doorUnlockedIcon)
elif(GPIO.input(sideDoorPin) == GPIO.LOW):
sideDoorLabel = Label(image = doorLockedIcon)
#main door:
if(GPIO.input(mainDoorPin) == GPIO.HIGH):
mainDoorLabel = Label(image = garageOpenIcon)
else:
mainDoorLabel = Label(image = garageClosedIcon)
mainDoorLabel.place(x = 50, y = 400)
sideDoorLabel.place(x = 150, y = 400)
root.after(1000, getDoors)
Here is my full code, images work but flicker:
# WeatherStation for Raspberry Pi Model B Rev 2
# steve.a.mccluskey#gmail.com
#
# Code adapted from youtube.com/watch?v=MWKAitSX3vg
# Channel educ8s.tv
# Video name "Raspberry Pi Project: Touch Weather Station using a DHT22 and a Raspberry Pi 3 with TKInter GUI
#
# This program uses readings from several Dallas DS18B20 temp sensors and displays on the LCD along with on a website.
# Temps are collected from a background process called updateSensors.py and written to a JSON file called sensorValues.JSON
# which is located in the web folder at /var/www/html/. This program reads the JSON file. The webpage also reads it so there's
# minimal interferance between programs.
# Sensors are zero indexed. The sensors are assigned to their respective labels by their index number.
# Use readSensors.py to print their index number, digital ID and current temp to the console.
#
# Door sensors are read directly from this program and displayed accordingly. updateDoor.py is also run in background to write to doorSensorValues.json
# also in the web folder to be served to the web page.
#
# Hardware Used:
# Raspberry Pi Model B Rev 2
# Adafruit PITFT - Assembled 480x320 3.5" TFT+Touchscreen For Raspberry Pi, adafruit.com/product/2097
# Adafruit Prototyping Pi Plate Kit for Raspberry Pi, adafruit.com/product/801
# Sparkfun RJ45 Breakout sparkfun.com/products/716
# Sparkfun RJ45 8-Pin Connector sparkfun.com/products/643
# Dallas OneWire DS18B20 Digital Temp Sensors
#
#
#
#
# ------------
# GPIO Pins used:
# 1 ) 3.3v -> orange -> 3.3v
# 2 ) 5.0v
# 3 ) SDA -> white/brown -> I2C SDA
# 4 ) 5.0v
# 5 ) SCL -> brown -> I2C SCL
# 6 ) Gnd -> white/orange -> Gnd
# 7 ) GPIO 7 -> GPIO 4 -> white/green -> OneWire Bus
# 8 ) TXD
# 9 ) Gnd
# 10) RXD
# 11) GPIO 0 -> GPIO 17
# 12) GPIO 1 -> GPIO 18
# 13) GPIO 2 -> GPIO 27 -> blue -> Main Door Sensor
#
# 14) Gnd
# 15) GPIO 3 -> GPIO 22 -> white/blue -> Side Door Sensor
# 16) GPIO 4 -> GPIO 23 -> green -> Side Door Lock Sensor
# 17) 3.3v
# 18) GPIO 5 -> GPIO 24 -> LCD Shield
# 19) SPI MOSI -> LCD Shield
# 20) Gnd
# 21) SPI MISO -> LCD Shield
# 22) GPIO 6 -> GPIO 25 -> LCD Shield
# 23) SPI SCLK -> LCD Shield
# 24) SPI CE0 -> LCD Shield
# 25) Gnd
# 26) SPI CE1 -> LCD Shield
# -------
# Cat5e Pinout :
# White/Orange : Gnd
# Orange : 3.3v
# White/Green : OneWire
# Blue : Main Door Sensor
# White/Blue : Side Door Sensor
# Green : Side Door Lock Sensor
# White/Brown : I2C SDA
# Brown : I2C SCL
from Tkinter import *
import Tkinter as tk
from Tkinter import Canvas
from PIL import ImageTk, Image
import threading
import tkFont
import RPi.GPIO as GPIO
import json
import time
import datetime
#temp sensor assignments:
livingRoom = 1
upstairs = 4
basement = 0
outside = 2
garage = 3
sammyDoor = 5
#digital door sensor pins:
mainDoorPin = 27
sideDoorPin = 22
sideDoorLockPin = 23
GPIO.setmode(GPIO.BCM)
GPIO.setup(mainDoorPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(sideDoorPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(sideDoorLockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
root = tk.Tk()
global garageOpenIcon
global garageClosedIcon
global doorUnlockedIcon
global doorLockedIcon
global doorOpenIcon
backgroundImage = PhotoImage(file = "background.gif")
garageOpenIcon = PhotoImage(file = "garageOpen.gif")
garageClosedIcon = PhotoImage(file = "garageClosed.gif")
doorLockedIcon = PhotoImage(file = "doorLocked.gif")
doorUnlockedIcon = PhotoImage(file = "doorUnlocked.gif")
doorOpenIcon = PhotoImage(file = "doorOpen.gif")
background = Label(root, image = backgroundImage)
background.place(x = 0, y = 0, relwidth = 1, relheight = 1)
global mainDoorLabel
global sideDoorLabel
global mainDoorState
global sideDoorState
mainDoorLabel = Label(root)
sideDoorLabel = Label(root)
#mainDoorLabel.place(x = 50, y = 400)
#sideDoorLabel.place(x = 150, y = 400)
#temp sensor strings:
mainTemp = StringVar()
mainTemp.set("In: ")
mainTempValue = StringVar()
outTemp = StringVar()
outTemp.set("Out:")
LR = StringVar()
LR.set("Living Room: ")
temperatureLR = StringVar()
UP = StringVar()
UP.set("Upstairs: ")
temperatureUp = StringVar()
DN = StringVar()
DN.set("Basement: ")
temperatureDn = StringVar()
Out = StringVar()
Out.set("Outside: ")
temperatureOut = StringVar()
Garage = StringVar()
Garage.set("Garage: ")
temperatureGg = StringVar()
SammyDoor = StringVar()
SammyDoor.set("SammyDoor: ")
temperatureSammyDoor = StringVar()
currentTime = StringVar()
timeStamp = StringVar()
#temp sensor labels:
mainTempLabel = Label(root, fg = "magenta2", background = "#00dbde", textvariable = mainTemp, font = ("Helvetica", 30))
mainTempLabel.place(x = 20, y = 195)
mainTempValueLabel = Label(root, fg = "magenta2", background = "#00dbde", textvariable = mainTempValue, font = ("Helvetica", 62, "bold"))
mainTempValueLabel.place(x = 100, y = 170)
outTempLabel = Label(root, fg = "magenta2", background = "#00dbde", textvariable = outTemp, font = ("Helvetica", 30))
outTempLabel.place(x = 20, y = 300)
outTempValueLabel = Label(root, fg = "magenta2", background = "#00dbde", textvariable = temperatureOut, font = ("Helvetica", 62, "bold"))
outTempValueLabel.place(x = 100, y = 260)
currentTimeLabel = Label(root, fg = "purple", background = "#00dbde", textvariable = currentTime, font = ("Helvetica", 30))
currentTimeLabel.place(x = 270, y = 5)
LRLabel = Label(root, fg = "white", background = "#00dbde", textvariable = LR, font = ("Helvetica", 25))
LRLabel.place(x = 391, y = 160)
temperatureLRLabel = Label(root, fg = "white", background = "#00dbde", textvariable = temperatureLR, font = ("Helvetica", 25, "bold"))
temperatureLRLabel.place(x = 600, y = 160)
UPLabel = Label(root, fg= "white", background = "#00dbde", textvariable = UP, font = ("Helvetica", 25))
UPLabel.place(x = 391, y = 210)
temperatureUpLabel = Label(root, fg = "white", background = "#00dbde", textvariable = temperatureUp, font = ("Helvetica", 25, "bold"))
temperatureUpLabel.place(x = 600, y = 210)
DNLabel = Label(root, fg = "white", background = "#00dbde", textvariable = DN, font = ("Helvetica", 25))
DNLabel.place(x = 391, y = 260)
temperatureDnLabel = Label(root, fg = "white", background = "#00dbde", textvariable = temperatureDn, font = ("Helvetica", 25, "bold"))
temperatureDnLabel.place(x = 600, y = 260)
GarageLabel = Label(root, fg = "white", background = "#00dbde", textvariable = Garage, font = ("Helvetica", 25))
GarageLabel.place(x = 391, y = 310)
temperatureGgLabel = Label(root, fg = "white", background = "#00dbde", textvariable = temperatureGg, font = ("Helvetica", 25, "bold"))
temperatureGgLabel.place(x = 600, y = 310)
SammyDoorLabel = Label(root, fg = "white", background = "#00dbde", textvariable = SammyDoor, font = ("Helvetica", 25))
SammyDoorLabel.place(x = 391, y = 360)
temperatureSammyDoorLabel = Label(root, fg = "white", background = "#00dbde", textvariable = temperatureSammyDoor, font = ("Helvetica", 25, "bold"))
temperatureSammyDoorLabel.place(x = 600, y = 360)
timeStampLabel = Label(root, fg = "white", background = "#00dbde", textvariable = timeStamp, font = ("Helvetica", 15))
timeStampLabel.place(x = 530, y = 440)
root.attributes("-fullscreen", True)
exitButton = tk.Button(root,fg = "white", text = "X", font = ("Helvetica", 20, "bold"), command = exit, bg = "red")
exitButton.place(x = 680, y = 0)
root.update_idletasks()
def exit():
root.quit()
def updateTemps():
index_value = []
id_value = []
temp_value = []
dateTime_value = []
#try reading json file. will not read if it is being written to by background process updateSensors.py
try:
with open('/var/www/html/sensorValues.json', 'r') as f:
data = f.read()
dataString = json.loads(data)
f.close()
for dateTime in dataString['timestamp']:
dateTime_value = (dateTime['dateTime'])
for index in dataString['sensors']:
temp_value.append(index['temp'])
id_value.append(index['id'])
index_value.append(index['index'])
temperatureLR.set(str(temp_value[livingRoom]) + " F")
temperatureOut.set(str(temp_value[outside]) + " F")
temperatureGg.set(str(temp_value[garage]) + " F")
temperatureUp.set(str(temp_value[upstairs]) + " F")
temperatureDn.set(str(temp_value[basement]) + " F")
temperatureSammyDoor.set(str(temp_value[sammyDoor]) + " F")
timeStamp.set(str(dateTime_value))
avg = format(float(((float(temp_value[livingRoom]) + float(temp_value[upstairs])) / 2.0)), '.1f')
mainTempValue.set(str(avg) + " F")
except:
pass
root.after(2000, updateTemps)
def getDoors():
global garageOpenIcon
global garageClosedIcon
global doorOpenIcon
global doorUnlockedIcon
global doorLockedIcon
global mainDoorLabel
global sideDoorLabel
# sideDoorState = 0
# mainDoorState = 0
#side door open and unlocked:
if(GPIO.input(sideDoorPin) == GPIO.HIGH):
# sideDoorState = 2
sideDoorLabel = Label(image = doorOpenIcon)
#closed and unlocked:
elif(GPIO.input(sideDoorPin) == GPIO.LOW):
if(GPIO.input(sideDoorLockPin) == GPIO.HIGH):
# sideDoorState = 1
sideDoorLabel = Label(image = doorUnlockedIcon)
elif(GPIO.input(sideDoorPin) == GPIO.LOW):
# sideDoorState = 0
sideDoorLabel = Label(image = doorLockedIcon)
#main door:
if(GPIO.input(mainDoorPin) == GPIO.HIGH):
# mainDoorState = 1
mainDoorLabel = Label(image = garageOpenIcon)
else:
mainDoorState = 0
mainDoorLabel = Label(image = garageClosedIcon)
mainDoorLabel.place(x = 50, y = 400)
sideDoorLabel.place(x = 150, y = 400)
root.after(1000, getDoors)
def getTime():
currentTime.set(datetime.datetime.now().strftime("%m-%d-%Y %H:%M:%S"))
root.after(500, getTime)
root.after(1000, getTime)
root.after(1001, updateTemps)
root.after(1000, getDoors)
root.mainloop()
maindoorlabel.configure(image = garageopenicon)
maindoorlabel.image = garageopenicon worked.