Plotting on python with matplotlib - python

I'm actually working on a schoolar project. We need to read and show the signals from 4 different sensors. I decided to make it using python instead matlab (simulink) because matlab doesn't recognize the raspberry pi 3. I already make a very simple guide whit Tkinter that read and show the values from sensor constantly and put it in a graph. The problem is that when I put the code to do the graphs it stops the refresh from the sensors and it shows the four values in one figure. The question(s) is(are):
How can I show the four values in four diferents graphs?
How can I make the refresh automatic?
How can in close all the figures using one button?
And if its possible can you tell me where can I found info to make more visual the graphics? How to customize de graphs.
Here is the code I have:
#IMPORTAR LIBRERIAS NECESARIAS
from Tkinter import *
from drawnow import *
import RPi.GPIO as GPIO
import matplotlib.pyplot as plt
import numpy
import tkFont
import time
import Adafruit_DHT
#Variables
trig = 16
echo = 18
pir = 15
distance = 0
distancia = 0
tiempo = 0
temp = 0
humd = 0
distanciaM = []
temperaturaM = []
presenciaM = []
humedadM = []
#DECLARAR ENTRADAS Y SALIDAS
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(trig, GPIO.OUT)
GPIO.setup(echo, GPIO.IN)
GPIO.setup(pir, GPIO.IN)
#VENTANAS
win = Tk()
plt.figure()
#TITULO DE LA VENTANA
win.title("Lectura sensores")
#DIMENSIONES DE INICIO
win.geometry('1050x500')
#FUENTES
myFont = tkFont.Font(family = 'Helvetica', size = 36)
titles = tkFont.Font(family = 'Helvetica', size = 50, weight = 'bold')
#FUNCIONES
##LEER SENSORES
def med():
###DISTANCIA
global distance
global distancia
global temp
global humd
GPIO.output(trig, False)
time.sleep(1)
GPIO.output(trig, True)
time.sleep(0.00001)
GPIO.output(trig, False)
while GPIO.input(echo)==0:
pulse_start = time.time()
while GPIO.input(echo)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
distancia.configure(text=str(distance))
distanciaM.append(str(distance))
print(distanciaM)
###PRESENCIA
i=GPIO.input(pir)
if i==1:
rb1.configure(text = str(i))
time.sleep(0.1)
else:
rb1.configure(text = str(i))
time.sleep(0.1)
presenciaM.append(str(i))
print (presenciaM)
###TEMPERATURA Y HUMEDAD
humidity, temperature = Adafruit_DHT.read_retry(11, 27)
temp = temperature
humd = humidity
templl.configure(text=str(temp))
humll.configure(text=str(humd))
temperaturaM.append(str(temp))
humedadM.append(str(humd))
print(temperaturaM)
print(humedadM)
###GRAFICAR
plt.plot(distanciaM, label ='Distancia','r')
plt.plot(presenciaM, label='Presencia', 'g')
plt.plot(temperaturaM, label='Temperatura', 'b')
plt.plot(humedadM, label='Humedad', 'y')
plt.show()
##LECTURA CONTINUA
def leccont():
med()
win.after(1000, leccont)
##SALIR DEL PROGRAMA
def exitProgram():
GPIO.cleanup()
win.quit()
#WIDGETS
##TITULO
titulo = Label(win, text="Lectura de cuatro sensores", font = titles)
titulo.grid(columnspan = 3)
##DISTANCIA
dist = Label(win, text = "Distancia:", font = myFont)
dist.grid(row = 1, column=0, sticky=W)
##ETIQUETA DISTANCIA
distancia = Label(win, text = "Distancia" , font=myFont)
distancia.grid(row=1, column=1)
##ETIQUETA UNIDADES DISTANCIA
cms=Label(win, text = "cms", font = myFont)
cms.grid(row = 1, column = 2)
##ETIQUETA PRESENCIA
pa=Label(win, text = "Presencia:", font = myFont)
pa.grid(row=2, column = 0, sticky=W)
##INDICADOR PRESENCIA
rb1 = Label(win, text = "No Presente", font = myFont)
rb1.grid(row = 2, column =1)
##TEMPERATURA
templ=Label(win, text="Temperatura:", font=myFont)
templ.grid(row=3,column=0,sticky=W)
##ETIQUETA TEMPERATURA
templl=Label(win, text="Temperatura", font=myFont)
templl.grid(row=3,column=1)
##ETIQUETA UNIDADES TEMPERATURA
tempu=Label(win, text = "C", font = myFont)
tempu.grid(row = 3, column = 2)
##HUMEDAD
huml=Label(win, text="Humedad relativa:", font=myFont)
huml.grid(row=4,column=0,sticky=W)
##ETIQUETA HUMEDAD
humll=Label(win, text="humedad", font=myFont)
humll.grid(row=4,column=1)
##ETIQUETA UNIDADES HUMEDAD
humu=Label(win, text = "HR", font = myFont)
humu.grid(row = 4, column = 2)
##MOSTRAR VALORES
medir=Button(win,text="Medir",font=myFont,command=med,height=1,width=6)
medir.grid(row=6,column=0)
##LECTURA CONTINUA
lecconti=Button(win, text="Medicion continua", font = myFont, command = leccont, height = 1, width = 15)
lecconti.grid(row = 6, column = 1)
##BOTON SALIR
exitButton = Button(win, text = "Salir", font = myFont, command = exitProgram, height = 1 , width = 6)
exitButton.grid(row = 6, column = 2)
mainloop()

I already solved it so here's the code:
# -*- coding: utf-8 -*-
#IMPORTAR LIBRERIAS NECESARIAS
from Tkinter import *
from drawnow import *
from matplotlib import style
import RPi.GPIO as GPIO
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy
import tkFont
import time
import Adafruit_DHT
#Variables
trig = 16
echo = 18
ldr = 15
distance = 0
distancia = 0
tiempo = 0
temp = 0
humd = 0
distanciaM = []
temperaturaM = []
resistenciaM = []
humedadM = []
style.use('fivethirtyeight')
#DECLARAR ENTRADAS Y SALIDAS
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(trig, GPIO.OUT)
GPIO.setup(echo, GPIO.IN)
GPIO.setup(ldr, GPIO.OUT)
#VENTANAS
win = Tk()
fig = plt.figure()
#TITULO DE LA VENTANA
win.title("Lectura sensores")
#DIMENSIONES DE INICIO
win.geometry('900x500')
#FUENTES
myFont = tkFont.Font(family = 'Helvetica', size = 36)
titles = tkFont.Font(family = 'Helvetica', size = 50, weight = 'bold')
#FUNCIONES
##LEER SENSORES
def med(i):
###DISTANCIA
global distance
global distancia
global temp
global humd
GPIO.output(trig, False)
time.sleep(1)
GPIO.output(trig, True)
time.sleep(0.00001)
GPIO.output(trig, False)
while GPIO.input(echo)==0:
pulse_start = time.time()
while GPIO.input(echo)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
distancia.configure(text=str(distance))
distanciaM.append(str(distance))
print(distanciaM)
###RESISTENCIA
count = 0
GPIO.setup(ldr, GPIO.OUT)
GPIO.output(ldr, GPIO.LOW)
time.sleep(0.1)
GPIO.setup(ldr, GPIO.IN)
while (GPIO.input(ldr) == GPIO.LOW):
count += 1
rb1.configure(text = str(count))
print count
resistenciaM.append(str(count))
print (resistenciaM)
###TEMPERATURA Y HUMEDAD
humidity, temperature = Adafruit_DHT.read_retry(11, 27)
temp = temperature
humd = humidity
templl.configure(text=str(temp))
humll.configure(text=str(humd))
temperaturaM.append(str(temp))
humedadM.append(str(humd))
print(temperaturaM)
print(humedadM)
###GRAFICAR
plt.plot(distanciaM, label ='Distancia',color='r')
plt.plot(resistenciaM, label='Resistencia', color='g')
plt.plot(temperaturaM, label='Temperatura', color='b')
plt.plot(humedadM, label='Humedad', color='k')
count = 0
##LECTURA CONTINUA
def leccont():
ani = animation.FuncAnimation(fig, med, interval=2000)
plt.legend()
plt.show()
win.after(1000, leccont)
##SALIR DEL PROGRAMA
def exitProgram():
GPIO.cleanup()
plt.close()
win.quit()
#WIDGETS
##TITULO
titulo = Label(win, text="Lectura de cuatro sensores", font = titles)
titulo.grid(columnspan = 3)
##DISTANCIA
dist = Label(win, text = "Distancia:", font = myFont)
dist.grid(row = 1, column=0, sticky=W)
##ETIQUETA DISTANCIA
distancia = Label(win, text = "Distancia" , font=myFont)
distancia.grid(row=1, column=1)
##ETIQUETA UNIDADES DISTANCIA
cms=Label(win, text = "Cms", font = myFont)
cms.grid(row = 1, column = 2)
##ETIQUETA RESISTENCIA
pa=Label(win, text = "Resistencia:", font = myFont)
pa.grid(row=2, column = 0, sticky=W)
##INDICADOR RESISTENCIA
rb1 = Label(win, text = "Resistencia", font = myFont)
rb1.grid(row = 2, column =1)
##ETIQUETA RESITENCIA
ohms=Label(win, text="Ohms", font = myFont)
ohms.grid(row=2, column = 2)
##TEMPERATURA
templ=Label(win, text="Temperatura:", font=myFont)
templ.grid(row=3,column=0,sticky=W)
##ETIQUETA TEMPERATURA
templl=Label(win, text="Temperatura", font=myFont)
templl.grid(row=3,column=1)
##ETIQUETA UNIDADES TEMPERATURA
tempu=Label(win, text = "C", font = myFont)
tempu.grid(row = 3, column = 2)
##HUMEDAD
huml=Label(win, text="Humedad relativa:", font=myFont)
huml.grid(row=4,column=0,sticky=W)
##ETIQUETA HUMEDAD
humll=Label(win, text="humedad", font=myFont)
humll.grid(row=4,column=1)
##ETIQUETA UNIDADES HUMEDAD
humu=Label(win, text = "HR", font = myFont)
humu.grid(row = 4, column = 2)
##LECTURA CONTINUA
lecconti=Button(win, text="Medicion", font = myFont, command = leccont, height = 1, width = 15)
lecconti.grid(row = 6, column = 0)
##BOTON SALIR
exitButton = Button(win, text = "Salir", font = myFont, command = exitProgram, height = 1 , width = 6)
exitButton.grid(row = 6, column = 2)
mainloop()

Related

Tkinter widgets becomes unresponsive while configuring them inside loop

I am trying to make a link monitoring application using python. Following is the code which I am using to monitor the link status.
import tkinter as tk
from tkinter import ttk
import tkinter.scrolledtext as scrolledtext
import telnetlib
import time
import datetime
import schedule
import winsound
duration = 2000 # milliseconds
freq_down = 880 # Hz
freq_up = 440 # Hz
import win32ui
window = tk.Tk()
window.geometry('950x700')
window.option_add('*Font', '19')
window.resizable(False, False)
window.title("Link Monitoring Application")
# Label
ttk.Label(window, text = "Select Link :",
font = ("Times New Roman bold", 16)).grid(column = 0,
row = 0, padx = (10, 5), pady = 15, sticky='EW')
n = tk.StringVar()
linkchoosen = ttk.Combobox(window, width = 47,
textvariable = n)
linkchoosen['values'] = ('LINK-1: 192.168.xx.xx',
'LINK-2: 192.168.xx.xx')
linkchoosen.grid(column = 1, row = 0, sticky='EW', padx = (10,15))
n.set('Select')
def chk_telnet(host_addr):
cb_data = host_addr
host_addr = cb_data.split(": ",1)[1]
host_name = cb_data.split(": ",1)[0]
tn = telnetlib.Telnet(host_addr)
tn.write(b"command\r\n")
time.sleep(5)
tn.write(b"exit\n")
output = tn.read_until(b"exit")
time.sleep(5)
tn.close()
output_str = output.decode('utf-8')
if "ALARMS = NONE" in output_str:
txt.insert(tk.INSERT, str(datetime.datetime.now()) + ' ' + host_name + " UP\n")
if ("LINK-1" in host_name):
btn_status_1.config(background = 'green')
elif ("LINK-2" in host_name):
btn_status_2.config(background = 'green')
# pass
elif ("ALARMS = LOCAL SYNC LOSS" in output_str):
txt.insert(tk.INSERT, str(datetime.datetime.now()) + ' ' + host_name + " DOWN\n")
if ("LINK-1" in host_name):
btn_status_1.config(background = 'red')
elif ("LINK-2" in host_name):
btn_status_2.config(background = 'red')
winsound.Beep(freq_down, duration)
elif ("ALARMS = REMOTE SYNC LOSS" in output_str):
# print("Link is Down")
txt.insert(tk.INSERT, str(datetime.datetime.now()) + ' ' + host_name + " DOWN\n")
if ("LINK-1" in host_name):
btn_status_1.config(background = 'red')
elif ("LINK-2" in host_name):
btn_status_2.config(background = 'red')
winsound.Beep(freq_down, duration)
def check_link_status():
host_addr = linkchoosen.get()
if ('Select' in host_addr):
win32ui.MessageBox("Please select a correct option", "Error")
return
else:
chk_telnet(host_addr)
schedule.run_pending()
window.after(1000, check_link_status)
btn = tk.Button(window, text = 'OK',font = ("Times New Roman bold", 12),
command = check_link_status)
btn.grid(column = 2, row = 0, sticky='EW', padx = (10,15))
btn_frame = tk.Frame(window)
btn_frame.grid(column = 1, row = 1, sticky='EW', padx = (10,15), pady =(10, 10))
btn_status_1 = tk.Button(btn_frame, text = 'LINK-1 STATUS', font = ("Times New Roman bold", 18), command = "", height = 3)
btn_status_1.pack(side = 'left')
btn_status_2 = tk.Button(btn_frame, text = 'LINK-2 STATUS', font = ("Times New Roman bold", 18), command = "", height = 3)
btn_status_2.pack(side = 'right')
txt_frame = tk.Frame(window)
txt_frame.grid(column = 0, row = 2, columnspan = 3, sticky='NSEW', padx
= (10,15), pady = (20, 10))
txt = scrolledtext.ScrolledText(txt_frame, undo=True)
txt['font'] = ('consolas', '12')
txt.grid(column = 0, row = 0, padx = (10,15), pady = (20, 10),
sticky='NSEW')
txt_frame.grid_rowconfigure(0, weight=1)
txt_frame.grid_columnconfigure(0, weight=1)
window.grid_rowconfigure(0, weight=1)
window.grid_columnconfigure(1, weight=1)
window.mainloop()
The above code is running fine and link up/down status are properly updated in the respective buttons and the same is entered as text in scrolled text box.
The issue which I am facing is - while the program is running then "clicking the dropdown button in combobox" or "clicking or selecting the text from textbox" makes GUI unresponsive.
Kindly suggest how to solve this issue so that the GUI becomes responsive.

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()

Write text into canvas python tkinter

I have all the gui configurations and all that stuff in my main.py and my algorithms to draw bubble sort and merge sort in another .py file. I'm trying to write the print functions into my canvas but I'm not sure how to do it, can anyone help? I tried using a ListBox() but it messes up the main canvas for some reason.
This is my code for my main file:
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from bubbleSort import bubbleSort
from mergeSort import mergeSort
tk = Tk()
tk.title('Examen Final')
tk.maxsize(900, 600)
tk.config(bg = 'black')
algoritmo = StringVar()
data = []
def dibujar(data, color):
c.delete("all")
cHeight = 380
cWidth = 600
algoWidth = cWidth / (len(data) + 1)
algoHeight = cWidth / (len(data) + 1)
offset = 20
spacing = 10
tamData = [i / max(data) for i in data]
for i, height in enumerate(tamData):
x0 = i * algoWidth + offset + spacing
y0 = cHeight - height * 50
x1 = (i+1) * algoWidth + offset
y1 = cHeight
c.create_oval(x0,y0,x1,y1, fill = color[i])
c.create_text(x0+2,y0, anchor = SW, text=str(data[i]))
tk.update_idletasks()
def Ordenar():
print("Se selecciono: " + algoritmo.get())
print("Iniciando algoritmo")
global data
if menu.get() == 'MERGE SORT':
mergeSort(data, dibujar)
elif menu.get() == 'BUBBLE SORT':
bubbleSort(data, dibujar)
dibujar(data, ['green' for x in range(len(data))])
def agregar():
global data
input = int(inputVal.get())
inputVal.delete(0, END)
try:
print("valor input:")
print(input)
data.append((input))
print(str(data))
dibujar(data, ['red' for x in range(len(data))])
except:
messagebox.showerror("Error", "Ingrese un valor numerico")
def limpiar():
global data
data = []
c.delete("all")
print(data)
box = Frame(tk, width = 600, height = 200, bg = 'black' )
box.grid(row = 0, column = 0, padx=10, pady=5)
c = Canvas(tk, width = 600, height = 380, bg = 'grey')
c.grid(row = 1, column = 0, padx=10, pady=5)
c2 = Canvas(tk, width = 200, height = 380, bg = 'grey')
c2.grid(row = 1, column = 1, padx=10, pady=5)
label = Label(box, text='Lista Algoritmos: ', font = ("Arial",15), borderwidth=1, bg = "black" , fg = 'white')
label.grid(row=0,column=0, padx=5, pady=5, sticky = W)
menu = ttk.Combobox(box, textvariable = algoritmo, values=['BUBBLE SORT', 'MERGE SORT', 'HASH TABLES', 'ARBOL AVL', 'ARBOLES ROJO Y NEGRO'])
menu.grid(row=0, column=1, padx=5, pady=5)
menu.current(0)
botonStart = Button(box, text = 'Ordenar', command = Ordenar, bg = 'lime green')
botonStart.grid(row = 0, column = 2, padx = 5, pady = 5)
label = Label(box, text='Insertar valor: ', font = ("Arial",15), borderwidth=1, bg = "black" , fg = 'white')
label.grid(row=1,column=0, padx = 5, pady = 5, sticky = W)
inputVal = Entry(box)
inputVal.grid(row=1,column=1, padx = 5, pady = 5, sticky = W)
botonAdd = Button(box, text = 'Agregar', command = agregar, bg = 'lime green')
botonAdd.grid(row = 1, column = 2, padx = 5, pady = 5, sticky = W)
botonClear = Button(box, text = 'Limpiar', command = limpiar, bg = 'lime green')
botonClear.grid(row = 1, column = 3, padx = 5, pady = 5, sticky = W)
tk.mainloop()
and this is my bubbleSort.py
import time
def bubbleSort(data, dibujar):
for _ in range(len(data)-1):
for j in range(len(data)-1):
if data[j] > data[j+1]:
print(("El numero " + str(data[j]) + " es mayor que " + str(data[j+1])))
data[j],data[j+1] = data[j+1], data[j]
print(("Intercambiando de lugar " + str(data[j]) + " con " + str(data[j+1])))
dibujar(data,
[
'green'
if x == j or x == j+1
else 'red' for x in range(len(data))
]
)
time.sleep(1)
dibujar(data, ['green' for x in range(len(data))])
You can just pass in c2 to the function on the other file. So first define the parameter:
def bubbleSort(data, dibujar, cnv):
cnv.create_text(100,100,text='Trial Text')
....
Now each time you call this function, pass on c2 to it.
if menu.get() == 'BUBBLE SORT':
bubbleSort(data, dibujar, c2)
I did notice that you are using dynamic points for calculation, if so, make those points global, inside the function, then pass those onto the function by creating more parameter, while keeping in mind that the points have to defined before the function is called.

Raspberry Pi Python Tkinter image flicker problem

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.

Insert while loop values to tkinter magic window

I have a code to create a "magic window" in python.
It should shows title, time and news.
I took news with function newz to loop (it should show the news on-by-on in Tkinter window)
I tried to insert it into tkinter label but it doesn't work(it just doesn't appear, but when I insert plain text to label it works), how could I do it? Here is the whole code with time functions and news function + tkinter
import tkinter as tk
from tkinter import *
import feedparser
import json
from time import sleep
import time
import os
startupscreen = tk.Tk()
startupscreen.title('Magic Mirror: Python Mod')
welcometext = tk.Label(startupscreen, font = ('caviar dreams', 40), bg='black', fg='white')
startupscreen.configure(background='black')
startupscreen.overrideredirect(True)
welcometext.config(text='日本')
welcometext.pack(side=LEFT, padx= 120, pady=80)
# Gets the requested values of the height and widht.
windowWidth = startupscreen.winfo_reqwidth()
windowHeight = startupscreen.winfo_reqheight()
# Gets both half the screen width/height and window width/height
positionRight = int(startupscreen.winfo_screenwidth()/3 - windowWidth/2)
positionDown = int(startupscreen.winfo_screenheight()/2 - windowHeight/2)
# Positions the window in the center of the page.
startupscreen.geometry("+{}+{}".format(positionRight, positionDown))
startupscreen.update()
decrypt = list()
global iteration
global timecount
global repull
global sleep
iteration = 0
timecount = 0
repull = 0
sleep = 0
# main window
while True:
def tick(time1=''):
time2 = time.strftime("%H")
if time2 != time1:
time1 = time2
clock_frame.config(text=time2)
clock_frame.after(200, tick)
def tickk(time3=''):
time4 = time.strftime(":%M:%S")
if time4 != time3:
time3 = time4
clock_frame2.config(text=time4)
clock_frame2.after(200, tickk)
def newz():
url = 'https://news.google.com/rss?hl=ja&gl=JP&ceid=JP:ja'
d = feedparser.parse(url)
news = list()
for i, entry in enumerate(d.entries, 1):
p = entry.published_parsed
sortkey = "%04d%02d%02d%02d%02d%02d" % (p.tm_year, p.tm_mon, p.tm_mday, p.tm_hour, p.tm_min, p.tm_sec)
tmp = {
"title": entry.title,
#"link": entry.link,
"sortkey": sortkey
}
news.append(tmp)
news = sorted(news, key=lambda x: x['sortkey'])
myDict = {}
for d in news:
c = d['title']
myDict[c] = myDict.get(c,0)+1
frequency = myDict.keys()
frequency = list(frequency)
for x in range(len(frequency)):
print (frequency[x])
x += 1
root = tk.Tk()
root.title('Mirror')
lab = Label(root, text=" 日本", font = ('', 40), bg='black', fg='white')
lab.pack(anchor=SW, fill=X, padx=45)
masterclock = tk.Label(root)
masterclock.pack(anchor=NW, fill=X, padx=45)
masterclock.configure(background='black')
clock_frame = tk.Label(root, font = ('caviar dreams', 130), bg='black', fg='white')
clock_frame.pack(in_=masterclock, side=LEFT)
clock_frame2 = tk.Label(root, font = ('caviar dreams', 70), bg='black', fg='white')
clock_frame2.pack(in_=masterclock, side=LEFT, anchor = N, ipady=15)
newstitle = tk.Label(root, font = ('caviar dreams', 30), bg='black', fg='white')
newstitle.pack(side=BOTTOM, anchor=W, fill=X)
source = tk.Label(root, font = ('caviar dreams', 20), bg='black', fg='white')
source.pack(side=BOTTOM, anchor=W, fill=X)
tick()
tickk()
newz() #here it doesnt work
root.attributes("-fullscreen", True)
root.configure(background='black')
startupscreen.destroy()
root.mainloop()
I don't know what you want to display but you have to use
source.config(text="some text")
root.after(1000, newz)
inside function newz
Something like this
#--- newz - start ---
def newz():
url = 'https://news.google.com/rss?hl=ja&gl=JP&ceid=JP:ja'
d = feedparser.parse(url)
news = list()
for i, entry in enumerate(d.entries, 1):
p = entry.published_parsed
sortkey = "%04d%02d%02d%02d%02d%02d" % (p.tm_year, p.tm_mon, p.tm_mday, p.tm_hour, p.tm_min, p.tm_sec)
tmp = {
"title": entry.title,
#"link": entry.link,
"sortkey": sortkey
}
news.append(tmp)
news = sorted(news, key=lambda x: x['sortkey'])
myDict = {}
for d in news:
c = d['title']
myDict[c] = myDict.get(c,0)+1
frequency = myDict.keys()
frequency = list(frequency)
for x in range(len(frequency)):
print(frequency[x])
source.config(text=str(frequency[x]))
x += 1
#source.config(text="some text")
root.after(1000, newz) # 1000ms = 1s
#--- newz - end ---

Categories