How do I create a 60 seconds countdown timer in kivy - python

I need to create a 60seconds countdown timer in kivy. It will start immediately when the code is run and it should print 'countdown completed' when the countdown is in 0.
Have not been able to derive any code for this. I just need a simple 60s countdown timer

As #Bryan Oakley mentioned:
Stackoverflow isn't designed to be a free code-writing service
but I love Kivy so maybe this will help someone someday...
from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock
class countDownClock(Label):
counter = 60
def update(self, *args):
if self.counter > 0:
self.text = str(self.counter -1)
self.counter -= 1
else:
self.text = "KaBoom"
class TimeApp(App):
def build(self):
countdown = countDownClock()
Clock.schedule_interval(countdown.update, 1)
return countdown
if __name__ == "__main__":
TimeApp().run()

this was developed using Tkinter,
from tkinter import *
import time, sys
window = Tk()
window.title("Countdown")
print('\nHello\nInstructions: add time.\n')
hourz = input('Hours: ')
minz = input('Minutes: ')
secz = input('Seconds: ')
hour = int(hourz); min = int(minz); sec = int(secz)
var = StringVar()
var.set("00:00:00")
label_title = Label(window, textvariable=var)
label_title.pack()
window.update()
print('Check the window !\n')
while hour > -1:
while min > -1:
while sec > 0:
sec = sec - 1
time.sleep(1)
sec1 = ('%02.f' % sec) # format
min1 = ('%02.f' % min)
hour1 = ('%02.f' % hour)
var.set('\r' + str(hour1) + ' : ' + str(min1) + ' : ' + str(sec1))
window.update()
min = min - 1
sec = 60
hour = hour - 1
min = 59
print(' Finish !\n')
window.mainloop()

Related

Python tKinter: How to pause countdown timer

I made a countdown timer that starts whenever I press on the space key on my keyboard, but the problem is that I can't do anything on the program until the timer ends. I want make it pause when the space key is pressed a second time.
The countdown timer that I made works in a while loop that ends when the timer reach 0, so the program waits until the loop ends before doing anything else, even if I want to stop the timer I can't do it while it's running.
Here's the code
from tkinter import *
from tkinter import ttk
import tkinter as tk
from PIL import ImageTk, Image
def StartTimer():
if (root.turn % 2) == 0: #Turn to white
root.number = '1'
root.color = 'white'
else: #Turn to black
root.number = '2'
root.color = 'black'
doTimer()
def doTimer():
root.time = root.minute *60 + root.second
root.turn = root.turn+1
number = root.number
root.rndsquare1.configure(image=root.green)
root.timer1.configure(bg='#1C953D')
root.white.configure(bg='#1C953D')
r=0
while r < root.time:
root.update_idletasks()
root.after(1000)
root.second = root.second - 1
if root.second == -1:
root.minute = root.minute -1
root.second = 59
root.time1 = ''
if len(str(root.minute)) == 1:
root.time1 = '0' + str(root.minute)
else:
root.time1 = str(root.minute)
if len(str(root.second)) == 1:
root.time1 = root.time1 + ':' + '0' + str(root.second)
else:
root.time1 = root.time1 + ':' + str(root.second)
root.timer1.configure(text=root.time1)
r=r+1
root.timer1.configure(bg='#454545')
root.white.configure(bg='#454545')
root.rndsquare1.configure(image=root.grey)
class root(Tk):
def __init__(self):
super(root, self).__init__()
self.title("Chess Clock")
self.minsize(1539,600)
self.windowBG = '#313131'
self.state('zoomed')
self.configure(bg=self.windowBG)
self.CreateWindow()
def CreateWindow(self):
self.grey = ImageTk.PhotoImage(Image.open(r"D:\Users\Jean Paul\OneDrive\Programming\Programs\Prog 6 - Chess Clock\bg square grey.png"))
self.green = ImageTk.PhotoImage(Image.open(r"D:\Users\Jean Paul\OneDrive\Programming\Programs\Prog 6 - Chess Clock\bg square green.png"))
self.turn=0
self.rndsquare1 = Label(self, image=self.grey, borderwidth=0)
self.rndsquare1.place(x=65, y=120)
self.rndsquare2 = Label(self, image=self.grey, borderwidth=0)
self.rndsquare2.place(x=809, y=120)
self.bind('<space>',lambda event:StartTimer())
self.createTimers()
def createTimers(self):
self.minute = 1
self.second = 5
self.time1 = ''
if len(str(self.minute)) == 1:
self.time1 = '0' + str(self.minute)
else:
self.time1 = str(self.minute)
if len(str(self.second)) == 1:
self.time1 = self.time1 + ':' + '0' + str(self.second)
else:
self.time1 = self.time1 + ':' + str(self.second)
self.time2 = ''
if len(str(self.minute)) == 1:
self.time2 = '0' + str(self.minute)
else:
self.time2 = str(self.minute)
if len(str(self.second)) == 1:
self.time2 = self.time2 + ':' + '0' + str(self.second)
else:
self.time2 = self.time2 + ':' + str(self.second)
self.timer1 = Label(self, text=self.time1, bg='#454545', fg='white', font ="Gadugi 40 bold")
self.timer1.place(x=330, y=420)
self.timer2 = Label(self, text=self.time2, bg='#454545', fg='white', font ="Gadugi 40 bold")
self.timer2.place(x=1080, y=420)
self.white = Label(self, text='White', bg='#454545', fg='white', font ="Gadugi 40 bold")
self.white.place(x=325, y=160)
self.black = Label(self, text='Black', bg='#454545', fg='white', font ="Gadugi 40 bold")
self.black.place(x=1075, y=160)
root=root()
root.mainloop()
D:\Users\Jean Paul\OneDrive\Programming\Programs\Prog 6 - Chess Clock\bg square grey.png
D:\Users\Jean Paul\OneDrive\Programming\Programs\Prog 6 - Chess Clock\bg square green.png
You can solve this by heavily refacturing your code. You can add 2 clocks to your widget, each clock tracks how much is spent on itself. The spacebar listener simply switches between which clock is currently in use. By also having a timed do_clock_logic every 200ms or so it checks if a current clock is set, if so if the time is up and if that is the case, switch over to the other clock. In any case it will trigger the clocks tick() method to update its internal states that also handle ui updates.
This way there is no "blocking" while loop and all timing stuff is handled by tk:
from tkinter import Tk, Label
import tkinter as tk
from PIL import ImageTk, Image
from datetime import datetime, timedelta
class clock():
"""A single clock that handles updating/timekeeping itself. It uses
the both class-level memebrs as active/inactive image and has
references provided to place the image and the timing text."""
active_img = None
deactive_img = None
#staticmethod
def format_time(delta, ms = False):
"""Returns a formatted strng for a timedelta instance,
optionally with milliseconds"""
return f"{delta.seconds//60:02}:{delta.seconds%60:02}" + (
f".{(delta.microseconds // 1000):04}" if ms else "")
def __init__(self, minutes, seconds, bg_lbl, text_lbl):
"""Set the clocks max duration providing 'minutes' and 'seconds'.
Provide tk-labels with a background image 'bg_lbl' and
'text_lbl' for the time display."""
self.max_duration = timedelta(seconds=seconds+minutes*60)
# UI
self.bg_lbl = bg_lbl,
self.text_lbl = text_lbl
# reset to inactive image and no text
self.bg_lbl[0].config(image = clock.deactive_img)
self.text_lbl.config(text = "")
# internal time keeping of total spent time1
self.total = timedelta() # 0 delta at start
def update_lbl(self, spent):
# update the image if needed
self.bg_lbl[0].config(image = clock.active_img if self.started is not None else clock.deactive_img)
# update labels - if not active - show with milliseconds
if self.started is not None:
self.text_lbl.config( text = clock.format_time(self.max_duration - spent))
else:
self.text_lbl.config(text = f"Total:\n{clock.format_time(self.total, True)}")
def start_clock(self):
# starts the clock
self.started = datetime.now()
self.update_lbl(timedelta())
def tick(self):
# ticks the clock - stops it if time has run out
if self.started is not None:
spent = datetime.now() - self.started
if spent > self.max_duration:
self._stop_clock(spent)
return False
self.update_lbl(spent)
return True
return None
def stop_clock(self):
# stop clock from the outside if <space> is hit
if self.started is not None:
spent = datetime.now() - self.started
self._stop_clock(spent)
def _stop_clock(self, spent):
# internal method that stops the clock, adds total & updates
spent = min(spent, self.max_duration) # fix it
self.total += spent
self.started = None
self.update_lbl(None)
class root(Tk):
def __init__(self):
super(root, self).__init__()
self.title("Chess Clock")
self.minsize(1539,600)
self.windowBG = '#313131'
self.state('zoomed')
self.configure(bg=self.windowBG)
self.CreateWindow()
def CreateWindow(self):
self.grey = ImageTk.PhotoImage(Image.open(r"grey.png"))
self.green = ImageTk.PhotoImage(Image.open(r"green.png"))
# used to determine player
self.turn = 0
# give the clock class the two images to switch
# if changing between active/inactive state
clock.deactive_img = self.grey
clock.active_img = self.green
# one clocks UI
self.white_bg = Label(self, image=self.grey, borderwidth=0)
self.white_bg.place(relx=.3, rely=.55, anchor="center")
self.white = Label(self, text='White', bg='#454545', fg='white', font ="Gadugi 40 bold")
self.white.place(relx=.3, rely=.2, anchor="center")
self.white_timer = Label(self.white_bg, text="", bg='#454545', fg='white', font ="Gadugi 40 bold")
self.white_timer.place(relx=.5, rely=.5, anchor="center")
# seconds clock UI
self.black_bg = Label(self, image=self.grey, borderwidth=0)
self.black_bg.place(relx=.7, rely=.55, anchor="center")
self.black = Label(self, text='Black', bg='#454545', fg='white', font ="Gadugi 40 bold")
self.black.place(relx=.7, rely=.2, anchor="center")
self.black_timer = Label(self.black_bg, text="", bg='#454545', fg='white', font ="Gadugi 40 bold")
self.black_timer.place(relx=.5, rely=.5, anchor="center")
# provide the background-label and the text label
# for time and create two clocks for the players
self.clock1 = clock(1, 5, self.white_bg, self.white_timer)
self.clock2 = clock(1,5, self.black_bg, self.black_timer)
# which clock is currently in use?
self.who_is_it = None
# handles switching to next players clock
self.bind('<space>', lambda _: self.next_player())
self.bind('<Control-Key-q>', lambda _: self.stop())
# check every 200ms if clocks need to be switched over
self.after(200, self.do_clock_logic)
def do_clock_logic(self):
# do nothing if no clock startet
# check if clock has run out, then switch to next players clock
if self.who_is_it is not None:
# tick() returns False if the player spent all his time
# tick() returns True if the player still has time
# tick() returns None if clock is not yet started
if self.who_is_it.tick() == False:
self.next_player()
# recheck clocks in 200ms
self.after(200, self.do_clock_logic)
def stop(self):
"""First Ctrl+q will stop clocks, second will quit."""
if self.who_is_it is not None:
self.who_is_it.stop_clock()
self.who_is_it = None
self.do_clock_logic = lambda _: None is None
else:
self.destroy()
def next_player(self):
if self.who_is_it is not None:
self.who_is_it.stop_clock()
self.turn += 1
# player 1 on "odd turns", player 2 on "even turns"
self.who_is_it = self.clock1 if self.turn % 2 else self.clock2
self.who_is_it.start_clock()
root=root()
root.mainloop()
to get
after the first CTRL+q you'll get the results - a second time CTRL+q closes your window:
This can be better structured regarding UI/logic stuff - but it works as proof of concept.

Running kivy and infinite loop at the same time

I need to make a countdown and then use it on mobile phone.
I heard that kivy is good graphic for mobile phones, so I tried to use this.
Im trying to run infinite while loop that will count down the time and the kivy app that will create window and display remaining time, both at the same time. I am also using pygame clocks to time it. But when I run this code the while loop is counting the time, but it only creates white blank window and after some time another window.
What am I doing wrong ?
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.uix.image import Image
from kivy.core.window import Window
from multiprocessing import Process
import pygame
class MyFloat(FloatLayout):
def __init__(self, **kwargs):
super(MyFloat, self).__init__(**kwargs)
self.background = Image(source="textures/background.jpg", allow_stretch=True, keep_ratio=False)
self.add_widget(self.background)
class MyApp(App):
def build(self):
return MyFloat()
def check_time():
global days
global hours
global minutes
global seconds
global miliSeconds
miliSeconds -= 1
if miliSeconds < 0:
miliSeconds += 100
seconds -= 1
if seconds < 0:
seconds += 60
minutes -= 1
if minutes < 0:
minutes += 60
hours -= 1
if hours < 0:
hours += 24
days -= 1
if days < 0:
global active
active = False
print("End")
print("days: ", days)
print("hours: ", hours)
print("minutes: ", minutes)
print("seconds: ", seconds)
print("miliseconds: ", miliSeconds)
def loop():
while active:
check_time()
clock.tick(100)
clock = pygame.time.Clock()
days = 0
hours = 0
minutes = 0
seconds = 30
miliSeconds = 0
active = True
if __name__ == "__main__":
p1 = Process(target=loop)
p2 = Process(target=MyApp().run)
p1.start()
p2.start()
Just change the last part of your code to:
if __name__ == "__main__":
p1 = Process(target=loop)
p1.start()
MyApp().run()
You don't need pygame nor while True because kivy has class Clock with functions
# call my_callback every 0.5 seconds
Clock.schedule_interval(my_callback, 0.5)
# call my_callback in 5 seconds
Clock.schedule_once(my_callback, 5)
# call my_callback as soon as possible (usually next frame.)
Clock.schedule_once(my_callback)
Start task:
task = Clock.schedule_interval(check_time, 0.1)
Stop task:
task.cancel()
And your function will get delta_time between executions so you can check if it was executed exactly after 0.1 second or not. And you can use this to display correct time.
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.uix.image import Image
from kivy.core.window import Window
from kivy.clock import Clock
class MyFloat(FloatLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.background = Image(source="textures/background.jpg", allow_stretch=True, keep_ratio=False)
self.add_widget(self.background)
class MyApp(App):
def build(self):
return MyFloat()
def check_time(dt):
global days
global hours
global minutes
global seconds
global miliSeconds
global active
miliSeconds -= 1
if miliSeconds < 0:
miliSeconds += 100
seconds -= 1
if seconds < 0:
seconds += 60
minutes -= 1
if minutes < 0:
minutes += 60
hours -= 1
if hours < 0:
hours += 24
days -= 1
if days < 0:
active = False
print("End")
task.cancel() # <-- stoping task
print("days: ", days)
print("hours: ", hours)
print("minutes: ", minutes)
print("seconds: ", seconds)
print("miliseconds: ", miliSeconds)
days = 0
hours = 0
minutes = 0
seconds = 1
miliSeconds = 0
active = True
if __name__ == "__main__":
task = Clock.schedule_interval(check_time, 0.1) # <-- starting task
MyApp().run()
EDIT:
Example which uses Clock to display current time in Label
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.clock import Clock
import datetime
class MyFloat(FloatLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.label = Label()
self.add_widget(self.label)
self.task = Clock.schedule_interval(self.update_label, 0.1)
def update_label(self, dt):
now = datetime.datetime.now()
self.label.text = now.strftime("%Y.%m.%d %H:%M.%S")
class MyApp(App):
def build(self):
return MyFloat()
if __name__ == "__main__":
MyApp().run()
BTW:
You may need multiprocessing/threading when you have to run long-running code. But it may need also Queue to communicate with main process. Usually GUIs can't modify widgets in separated processes/threads.

Clock and counter in the same window

I can't remove a label from this code at the end of countdown
the idea is to have a clock and a countdown timer for an event and at the end of the counter I want it to disappear.
from tkinter import *
import time
win = Tk()
win.geometry('400x400')
frame=Frame(win)
frame.grid()
labelTD=Label(frame)
labelTD.grid(row=2,column=0)
def clock():
t=time.strftime('%A''\n''%D''\n''%I:%M:%S',time.localtime())
if t!='':
labelTD.config(text=t,font='infra 50 bold',foreground='black',background='white')
labelTD.update_idletasks()
labelTD.after(1000,clock)
def countdown():
for t in range(12,-1,-1):
Mn = t % 60
Hr = t // 60
if int(Hr)<10 and int(Mn)<10:
xmn = str(Mn).zfill(2)
xhr = str(Hr).zfill(2)
label1 = Label(frame, text=(xhr+':'+xmn))
label1.grid(row=1)
else:
label1 = Label(frame, text=(str(Hr).zfill(2)+':'+str(Mn)))
label1.grid(row=1)
frame.update()
time.sleep(1)
labelTD.grid(row=2,column=0)
clock()
countdown()
win.mainloop()
You should use after() for the countdown as well and create the label for countdown outside the function:
labelCD = Label(frame)
labelCD.grid()
def countdown(n):
hr, mn = divmod(n, 60)
labelCD.config(text=f"{hr:02}:{mn:02}")
if n > 0:
labelCD.after(1000, countdown, n-1)
else:
labelCD.destroy()
countdown(12)
Update: Show hh:mm:ss in countdown():
def countdown(n):
mn, secs = divmod(n, 60)
hr, mn = divmod(mn, 60)
labelCD.config(text=f"{hr:02}:{mn:02}:{secs:02}")
if n > 0:
labelCD.after(1000, countdown, n-1)
else:
labelCD.destroy()

Building a application with TKInter, need some assistance

Basically, I've made a GUI application for personal use related to an online gaming community, and I'm kind've stuck currently. It is working as intended, apart from one thing. I need it to be able to track multiple "Activations" and start separate timers but keep track of the previous timers as well, so it can total it up at the end. For example, if I Activate "Service 1" it currently starts a timer, but when I deactivate it and activate it once again, it will disregard the initial timer and just start a new one. How can I make it so it adds the two timers together to print out a "total time spent".
Here is the code relevant to my query
def time_convert3(sec):
global PALenght
mins = sec // 60
sec = round(sec % 60)
hours = mins // 60
mins = mins % 60
SIDLenght = ("{0}H:{1}M:{2}S".format(int(hours),int(mins),sec))
print(PALenght)
def selectPA():
global PAStart
global PALenght
global PACount
if var.get() == 1:
PAStart = time.time()
print(PAStart)
PACount = PACount + 1
root.after(10, lambda: Label(root, text= 'PA Activations: ' + str(PACount), bg='#1aa3ff', fg='Black' ).place(relx=0.1, rely=0.85, relwidth=0.3, relheight=0.05))
root.after(1000, lambda: portA.place(relx=0.4, rely=0.55, relwidth=0.2, relheight=0.05))
root.after(3000, lambda: portA.place_forget())
elif var.get() == 0:
PAEnd = time.time()
PATotal = PAEnd - PAStart
time_convert3(PATotal)
root.after(1000, lambda: portB.place(relx=0.4, rely=0.55, relwidth=0.2, relheight=0.05))
root.after(3000, lambda: portB.place_forget())
var = IntVar()
PACheck = Checkbutton(root, text="Activate/Deactivate PA ", variable = var,bg='#1aa3ff', fg='Black', command = selectPA).place(relx=0.13, rely=0.55, relwidth=0.2, relheight=0.05)
At start you should set
PATotal = 0
and later add new time to total
PATotal += (PAEnd - PAStart)
Minimal working example
import tkinter as tk
import time
# --- functions ---
def func():
global total
global time_start
if cb_var.get():
time_start = time.time()
else:
total += (time.time() - time_start)
label['text'] = 'Total: {:.2f}s'.format(total)
# --- main ---
total = 0
time_start = 0
root = tk.Tk()
cb_var = tk.BooleanVar()
label = tk.Label(root, text='Total: 0.00s')
label.pack()
cb = tk.Checkbutton(root, text='Running ...', variable=cb_var, command=func)
cb.pack()
root.mainloop()
Or at start you create list
all_times = []
and later append PAEnd - PAStart to this list
all_times.append(PAEnd - PAStart)
and you can sum all values on list.
PATotal = sum(all_times)
Minimal working example
import tkinter as tk
import time
# --- functions ---
def func():
global total
global time_start
if cb_var.get():
time_start = time.time()
else:
all_times.append(time.time() - time_start)
label_times['text'] += '\n{:.2f}'.format(all_times[-1])
total = sum(all_times)
label_total['text'] = 'Total: {:.2f}s'.format(total)
# --- main ---
all_times = []
total = 0
time_start = 0
root = tk.Tk()
cb_var = tk.BooleanVar()
label_times = tk.Label(root, text='Times')
label_times.pack()
label_total = tk.Label(root, text='Total: 0.00s')
label_total.pack()
cb = tk.Checkbutton(root, text='Running ...', variable=cb_var, command=func)
cb.pack()
root.mainloop()

Function to check distance using ultrasonic sensor freezes tkinter

I'm using trying to use python with an ultrasonic sensor to measure distance, and then update a tkinter label with the distance value every second. However, I'm having problems; it will run for a while, anything from a couple of seconds up to a few minutes, then freeze.
Here is my code:
from tkinter import *
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO_TRIGGER_X = 4
GPIO_ECHO_X = 27
GPIO.setup(GPIO_TRIGGER_X, GPIO.OUT)
GPIO.setup(GPIO_ECHO_X, GPIO.IN)
def distanceX():
GPIO.output(GPIO_TRIGGER_X, True)
time.sleep(0.0001)
GPIO.output(GPIO_TRIGGER_X, False)
StartTime = time.time()
StopTime = time.time()
while GPIO.input(GPIO_ECHO_X) == 0:
StartTime = time.time()
while GPIO.input(GPIO_ECHO_X) == 1:
StopTime = time.time()
TimeElapsed = StopTime - StartTime
distance = (TimeElapsed * 34300) / 2
return distance
def updateDistance():
dX = distanceX()
print(dX)
lengthValue.configure(text=dX)
root.after(1000, updateDistance)
root = Tk()
root.geometry("200x100")
root.tk_setPalette(background="white", foreground="black")
lengthName = Label(root, text = "Length:")
lengthValue = Label(root, text="start")
lengthName.grid(row=1, column=1)
lengthValue.grid(row=1, column=2)
updateDistance()
root.mainloop()
I have tried running distanceX() alone in a separate script just printing out the values, that works fine. I've also tried the running the script without distanceX() like this:
dX = 0
def updateDistance():
global dX
print(dX)
lengthValue.configure(text=dX)
dX += 1
root.after(1000, updateDistance)
..and that also works fine.
Any ideas?
Apologies in advance if I've left any needed info out, this is my first go at python and tkinter...
Tkinter is single threaded. Your while loop in function distanceX blocks the main thread until it receives a True value and continues with the rest of the function. That's why you are experiencing freezes.
Try run the below:
from tkinter import *
import time
root = Tk()
flag = True
def something():
global flag
while flag:
print ("Hello World")
time.sleep(1)
def set_flag():
global flag
flag = False
something()
root.after(2000,set_flag)
root.mainloop()
And you will see your Tk window won't even pop up due to While loop blocking the main thread.
To solve this, you need to thread your distanceX() function. Something like:
from tkinter import *
import threading, time
root = Tk()
flag = True
def something():
global flag
while flag:
print ("Hello world")
time.sleep(1)
def set_flag():
global flag
flag = False
t = threading.Thread(target=something)
t.start()
root.after(2000,set_flag)
root.mainloop()
You can read more about threading in here.
Turns out the problem was in fact the two while loops in distanceX(). Added a timeout to both and all is well. Working code:
from tkinter import *
import RPi.GPIO as GPIO
import threading, time
GPIO.setmode(GPIO.BCM)
GPIO_TRIGGER_X = 4
GPIO_ECHO_X = 27
GPIO.setup(GPIO_TRIGGER_X, GPIO.OUT)
GPIO.setup(GPIO_ECHO_X, GPIO.IN)
def distanceX():
while True:
timeout = time.time() + 0.1
GPIO.output(GPIO_TRIGGER_X, True)
time.sleep(0.0001)
GPIO.output(GPIO_TRIGGER_X, False)
StartTime = time.time()
StopTime = time.time()
while GPIO.input(GPIO_ECHO_X) == 0:
StartTime = time.time()
if time.time() > timeout:
break
while GPIO.input(GPIO_ECHO_X) == 1:
StopTime = time.time()
if time.time() > timeout:
break
TimeElapsed = StopTime - StartTime
distance = (TimeElapsed * 34300) / 2
print(distance)
lengthValue.configure(text=distance)
time.sleep(1)
def check():
print("All good")
root = Tk()
root.geometry("200x100")
root.tk_setPalette(background="white", foreground="black")
lengthName = Label(root, text = "Length:")
lengthValue = Label(root, text="start")
button = Button(root, text="Check", command=check)
lengthName.grid(row=1, column=1)
lengthValue.grid(row=1, column=2)
button.grid(row=2, column=1)
t1 = threading.Thread(target=distanceX)
t1.start()
root.mainloop()

Categories

Resources