How do I get this timer to count down properly? - python

I am trying to make a simple gui where you can press a button to start a a timer, and see it count down, similar to https://web.5217.app/, But I cannot get the timer to display in the gui, any help would be appreciated.
Also this is my first question so I may have done something wrong.
from tkinter import Tk, Button, DISABLED, Label, ACTIVE
import time
#main window configuration
root = Tk()
root.title ("PyDoro")
root.geometry ("400x400")
root.configure(bg = "#383838")
#colours for the text
Colour1 = "#c4c4c4"
Colour2 = "#292828"
def Date(): #Defines the date for displaying under the clock
day = time.strftime("%d")
month = time.strftime("%b") # %B can be used for full month
year = time.strftime("%Y")
Calendar.config (text= day + " " + month + " " + year)
def clock(): # for creating the clock
tizo = time.strftime("%X") #Find the time for your locale
Time.config (text = tizo)
Time.after (1000, clock)
Date() #calling the Date because it makes sense to do it here
def Stop():
print ("nothing")
def Start():
time_left = (50)
Stop.config (state = ACTIVE)
timer = Label (root, text = time_left)
timer.pack()
for i in range (50):
timer.config (text = time_left)
Start.after (1000) # this waits for 1 minute (60000 miliseconds)
#print (i) # This is just for debugging
time_left = time_left - 1
print (time_left)
Start = Button (root, text = "Start!", fg = Colour1, bg = Colour2, padx = 40, command = Start)
Stop = Button (root, text = "stop", fg = Colour1, bg = Colour2, state = DISABLED)
Time = Label (root, text="", font = ("Helvetica", 50), fg = Colour1, bg = "#383838")
Time.pack (pady = 5)
Calendar = Label (root, font = ("Helvetica", 12), fg = Colour1, bg = "#383838")
Calendar.pack (pady = 5)
Start.pack (pady = 10)
Stop.pack (pady = 10)
clock()
root.mainloop() #Runs the program

Replace your Start() function with the following code:
def Start():
time_left = (50)
Stop.config (state = ACTIVE)
timer = Label (root, text = time_left)
timer.pack()
def update(time_left):
timer['text'] = time_left
if time_left > 0:
root.after(1000, update, time_left-1)
update(time_left)
After you create your label, the program calls a function called update, which sets the text of the timer label to time_left. It will then call root.after if time_left is greater than 0, and it passes time_left -1 back into the update function. This will make the timer countdown until it reaches 0.

The reason the timer Label isn't being shown is because the display is never given a chance to update. To fix that, try using the Start() function shown below which calls the universal widget method update_idletasks() to update it after it's been changed.
def Start():
time_left = 50
Stop.config(state=ACTIVE)
timer = Label(root, text=time_left)
timer.pack()
for i in range(50):
timer.config(text=time_left)
time_left -= 1
root.update_idletasks() # Update display.
root.after(1000) # Pause for 1000 milliseconds (1 second).

Related

Reaction Time Game counting rong (Python 3.10)

I'm making a reaction time game. description: Tkinter GUI, after random time a box with random color, size, font, place appears. openpyxl to save the game data if player wants to, threading for counting the seconds used, DateTime to put inside excel sheet for game data, random to choose place, size, font, color, text in box.
the intended game is that you get a box that appears after some time, you click, that box as fast as you can, it loops over that 3 times, when 3 times is finished you get a stats GUI with the time each of the 3 times, average time, save btn, play again btn.
error: the error is that the game counts wrong, if you try the game you will see that when the stats GUI come up all the time will be incremented by 0.01, example:
time 1: 1.15
time 2: 1.16
time 3: 1.17
if someone could point out the error that would be amazing.
code:
from tkinter import *
from tkinter import messagebox
from time import sleep
import openpyxl
import datetime
import random
import threading
def run_game():
root = Tk()
root.title("Reaction Time Game")
root.iconbitmap("C:/Users/Axelr/PycharmProjects/PC01/main/Self built/Reaction Time Game/icon.ico")
root.geometry("1400x1000")
root.configure(bg="orange")
workbook = openpyxl.load_workbook(filename="time_data.xlsx")
sheet = workbook.active
time_used_list = []
first_run = True
def clicked3():
global keep_counting
keep_counting = False
root.destroy()
root2 = Tk()
root2.title("Reaction Time Game Completed")
root2.iconbitmap("C:/Users/Axelr/PycharmProjects/PC01/main/Self built/Reaction Time Game/icon.ico")
root2.geometry("700x570")
root2.configure(bg="lightblue")
def save():
current_datetime = datetime.datetime.now()
current_datetime = current_datetime.strftime("%Y-%m-%d | %H:%M")
place = sheet.max_row + 1
sheet[f"A{place}"] = round(time_used_list[0], 2)
sheet[f"B{place}"] = round(time_used_list[1], 2)
sheet[f"C{place}"] = round(time_used_list[2], 2)
average = sum(time_used_list) / len(time_used_list)
sheet[f"D{place}"] = round(average, 2)
sheet[f"E{place}"] = current_datetime
workbook.save(filename="time_data.xlsx")
print("Saved time data")
def run_another():
root2.destroy()
run_game()
print("list of times:")
for time in time_used_list:
print(time)
title_label = Label(root2, text="Results", font=("Arial", 20, "bold"), bg="orange")
title_label.pack(padx=20, pady=20)
time1_label = Label(root2, text=f"Time used 1: {round(time_used_list[0], 2)} seconds", font=("Arial", 20), bg="orange")
time1_label.pack(padx=20, pady=20)
time2_label = Label(root2, text=f"Time used 2: {round(time_used_list[1], 2)} seconds", font=("Arial", 20), bg="orange")
time2_label.pack(padx=20, pady=20)
time3_label = Label(root2, text=f"Time used 3: {round(time_used_list[2], 2)} seconds", font=("Arial", 20), bg="orange")
time3_label.pack(padx=20, pady=20)
average_time = sum(time_used_list) / len(time_used_list)
average_label = Label(root2, text=f"Average Time Used: {round(average_time, 2)} seconds", font=("Arial", 20), bg="orange")
average_label.pack(padx=20, pady=20)
save_btn = Button(root2, text="Save", font=("Arial", 20), command=save, bg="orange")
save_btn.pack(padx=20, pady=20)
play_btn = Button(root2, text="Play Again", font=("Arial", 20), bg="orange", command=run_another)
play_btn.pack(padx=20, pady=20)
root2.mainloop()
def clicked():
global keep_counting, times_clicked, first_run
keep_counting = False
if times_clicked == 2:
clicked3()
else:
times_clicked += 1
btn.destroy()
print(first_run)
print(times_clicked)
first_run = False
start(first_run)
def time_thread():
global time_used
time_used = 0.00
while keep_counting:
sleep(0.01)
time_used += 0.01
time_used_list.append(time_used)
def start(first):
global keep_counting, times_clicked, first_run
if first:
times_clicked = 0
first_run = False
color_list = ["red", "green", "yellow", "cyan", "white", "blue", "magenta"]
random_color = random.choice(color_list)
random_x = random.randint(100, 600)
print(f"random_x = {random_x}")
random_y = random.randint(100, 600)
print(f"random_y = {random_y}")
random_width = random.randint(5, 15)
random_height = random.randint(5, 20)
print(f"random_width = {random_width}, random_height = {random_height}")
font_list = ["Helvetica", "Garamond", "Frutiger", "Bodoni", "Times", "Futura"]
random_font = random.choice(font_list)
random_font_size = random.randint(10, 18)
print(f"Font = {random_font}, font_size = {random_font_size}")
text_list = ["!", "?", "/", "+", "=", "<", ">", "%", "&", "(", ")", "-", "|", ";", ":", "[", "]", "{", "}", "^",
"#", "#"]
random_text = random.choice(text_list)
print(f"Random text = {random_text}")
random_time = random.randint(3, 5)
print(f"Random time = {random_time}")
thread = threading.Thread(target=time_thread)
keep_counting = True
def btn_create():
global btn
btn = Button(root, text=random_text, font=(random_font, random_font_size), bg=random_color, width=random_width, command=clicked)
btn.place(x=random_x, y=random_y)
thread.start()
time_wait = random_time * 1000
root.after(time_wait, btn_create)
start(first_run)
root.mainloop()
run_game()
please help me.
Your time_thread assumes that a sleep of 0.01 seconds always takes 0.01 seconds. That is patently false. Sleep merely guarantees you will wait for AT LEAST 0.01 seconds. On Windows, for example, the scheduler interval is about 0.016 seconds, so you can never sleep less than that. You can fix that by changing your timing thread to just snapshot the time before and after.
def time_thread():
start = time.time()
while keep_counting:
time.sleep(0.01)
time_used_list.append(time.time()-start)
HOWEVER, even that has a huge flaw. The problem here is that, because of Python's interpreter lock, it's quite possible for keep_counting to be set False and then True again before the time_thread gets a chance to run, in which case it will just keep running. You end up with all three time_threads counting at once.
You don't need that loop. Just capture the starttime when you display the button, and capture the end time when it is clicked. Eliminate keep_counting and the time thread altogether. This eliminated the need for importing threading at all.
So:
def run_game():
root = Tk()
root.title("Reaction Time Game")
root.geometry("1400x1000")
root.configure(bg="orange")
starttime = 0
time_used_list = []
first_run = True
def clicked3():
root.destroy()
root2 = Tk()
...
def clicked():
global times_clicked, first_run
time_used_list.append(time.time()-starttime)
if times_clicked == 2:
clicked3()
...
random_time = random.randint(3, 5)
print(f"Random time = {random_time}")
def btn_create():
global btn
btn = Button(root, text=random_text, font=(random_font, random_font_size), bg=random_color, width=random_width, command=clicked)
btn.place(x=random_x, y=random_y)
starttime = time.time()
time_wait = random_time * 1000
root.after(time_wait, btn_create)
As a rule, don't count elapsed time using a thread. Just grab a start time and an end time and subtract.

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.

countdown timer overlay in python with keypress Tkinter

Hello I am trying to make a simple script which on key press x starts a timer of 45 sec after that when it reaches 10 sec color text changes to red and when countdown comes 0 I want to destroy the timer gui but not the program, and when i press x again program starts doing stuff again and repeats the process
So far I managed this I tried all day I also tried adding on keypress but it become so complicated and didn't worked so I am asking help here
from tkinter import *
root = Tk()
root.geometry("112x55")
root.overrideredirect(True)
root.lift()
root.wm_attributes("-topmost", True)
root.wm_attributes("-disabled", True)
root.wm_attributes("-transparentcolor", "white")
root.resizable(0, 0)
seconds = 45
def timer():
global seconds
if seconds > 0:
seconds = seconds - 1
mins = seconds // 60
m = str(mins)
if mins < 10:
m = '0' + str(mins)
se = seconds - (mins * 60)
s = str(se)
if se < 10:
s = '0' + str(se)
time.set(m + ':' + s)
timer_display.config(textvariable=time)
# call this function again in 1,000 milliseconds
root.after(1000, timer)
elif seconds == 0:
seconds.delete("1.0","end")
frames = Frame(root, width=500, height=500)
frames.pack()
time = StringVar()
timer_display = Label(root, font=('Trebuchet MS', 30, 'bold'))
timer_display.place(x=0, y=0)
timer() # start the timer
root.mainloop()
As you used wm_attributes('-transparentcolor', 'white') (but you never set the background color of root and the timer_display to white, so it don't have effect) and overrideredirect(True), that means you want the window totally transparent and borderless. However this has side effect that you may never get the window focus back after the window loses focus.
Also you used wm_attributes('-disabled', True), then you can't have any key press event triggered. It should not be used.
Suggest to use wm_attributes('-alpha', 0.01) to simulate the transparent effect without the above issues.
Below is an example:
from tkinter import *
root = Tk()
root.geometry("+0+0")
root.overrideredirect(True)
root.wm_attributes("-topmost", True)
root.wm_attributes("-alpha", 0.01)
root.resizable(0, 0)
seconds = 45
def countdown(seconds):
if seconds > 0:
mins, secs = divmod(seconds, 60)
timer_display.config(text="{:02d}:{:02d}".format(mins, secs),
fg='red' if seconds <= 10 else 'white')
root.after(1000, countdown, seconds-1)
else:
root.wm_attributes('-alpha', 0.01) # make the window "disappear"
def start_countdown(event):
root.wm_attributes('-alpha', 0.7) # make the window "appear"
countdown(seconds)
timer_display = Label(root, font=('Trebuchet MS', 30, 'bold'), bg='black')
timer_display.pack()
root.bind('x', start_countdown)
root.bind('q', lambda e: root.destroy()) # provide a way to close the window
root.mainloop()
NOTE #1: If the window loses focus, you can still click somewhere near the top-left corner of the screen to resume window focus, although you cannot see the window.
NOTE #2: If you want system-wise key handler, tkinter does not support it. You need to use other module, like pynput.
If you want to destroy the timer GUI, You'll need to make a class like this:
class Timer(Frame):
def __init__(self, master):
super().__init__(master)
# Paste the code you want to run here, make sure you put "self." before it.
# For example:
def clicked():
print('Clicked!')
self.myButton = Button(self, text="Click me!", border=0, width=25, height=1, command=self.clicked)
self.logbtn.grid(columnspan=2)
self.pack()
if seconds == 0:
self.destroy() # by using self.destroy(), you tell it to delete the class.
else:
# You can put whatever you want it to do if it's not 0 here.
tm = Timer(root)
You can bind functions to keystroke events with root.bind(event, callback).
If you are using Linux or Mac, root.overrideredirect(True) will
prevent your application from receiving keystroke events. You can read
more here: Tkinter's overrideredirect prevents certain events in Mac and Linux
Example:
def keydown(e):
print(f"Key pressed: ")
print("Key code:", e.keycode)
print("Key symbol:", e.keysym)
print("Char:", e.char)
def keyup(e):
print(f"Key '{e}' released")
root.bind("<KeyPress>", keydown)
root.bind("<KeyRelease>", keyup)
root.focus_set()
Alternatively, you can also bind to specific keys with <Key-KEYSYM>, e.g. <Key-space> for the spacebar. A list with all keysyms can be found here
Some more events are listed here
Implementation example
Here is an example with a custom CountdownLabel class that is derived from tkinter.Label and automatically binds to the spacebar key event.
app.py
from countdown import CountdownLabel
from tkinter import Frame, StringVar, Tk, Button
root = Tk()
root.geometry("120x60")
root.lift()
root.wm_attributes("-topmost", True)
root.resizable(0, 0)
# Not supported on Linux and MacOS
# root.overrideredirect(True)
# root.wm_attributes("-disabled", True)
# root.wm_attributes("-transparentcolor", "white")
timer_display = CountdownLabel(root, 10, 5)
timer_display.pack(fill="both", expand=True)
timer_display.configure(background="white")
timer_display.configure(font=('Trebuchet MS', 26, 'bold'))
timer_display.focus_set()
root.mainloop()
countdown.py
from tkinter import Label
class CountdownLabel(Label):
# context : A reference to the Label in order to change the text and
# to close it later on
# duration: Total time in seconds
# critical: Length of the last timespan before the countdown finishes
# in seconds
def __init__(self, context, duration, critical):
super().__init__(context)
self.duration = duration
self.critical = critical if duration >= critical else duration
self.update_ui()
self.bound_sequence = "<Key-space>"
self.bound_funcid = self.bind(self.bound_sequence, self.get_handler())
# Returns a function for the event binding that still has access to
# the instance variables
def get_handler(self):
# Gets executed once when the counter starts through handler() and calls
# itself every second from then on to update the GUI
def tick():
self.after(1000, tick)
self.update_ui()
self.duration -= 1
# Gets executed when time left is less than <critical> (default = 10s)
# Sets the font color to red
def change_font_color():
self.configure(foreground="red")
# Destroys itself after the countdown finishes
self.after((self.critical + 1) * 1000, lambda : self.destroy())
def handler(event):
self.unbind(self.bound_sequence, self.bound_funcid)
self.bound_funcid = -1
self.bound_sequence = None
self.after((self.duration - self.critical) * 1000, change_font_color)
tick()
return handler
# Updates the displayed time in the label
def update_ui(self):
mm = self.duration // 60
ss = self.duration % 60
self.config(text="%02d:%02d" % (mm, ss))
def change_binding(self, sequence):
if self.bound_funcid > 0:
self.unbind(self.bound_sequence, self.bound_funcid)
self.bound_sequence = sequence
self.funcid = self.bind(self.bound_sequence, self.get_handler())

make a window flash like wrning signal light specific number of times and carry out some function after it

i want to make a notifying application in python using tkinter.
i want to check the system time if it matches the time from database time field of any row a window show flash on and off some specific number of times like danger warning lights.after the flashes finished those number of times a window should come showing about the events/scheduled that are to notified to the user.
i have tried to write the code but it makes the window appear only once.
i have tried using the root.after method of tkinter but dont know how to implement the requirements i want in the application.
#repeatedly checking if system time matched any teachers scedule time--------------------------------
def repeatedquery():
def alertmsg():
for j in range (4):
newteacheradd.withdraw()
messagewindow = Toplevel()
#to come out press alt+escape
messagewindow.wm_attributes("-fullscreen", 1)
messagewindow.title("Notification")
msgflash = Label(messagewindow, text='Notice', bg="#1f618d", fg='white', font=("Verdana", 28, 'bold'),
height=5,width=40, relief=RAISED)
msgflash.place(x=150, y=300)
print ("hjgj")
time.sleep(10)
messagewindow.after(15000, messagewindow.withdraw)
messagewindow.mainloop()
def showMesagewin():
newteacheradd.withdraw()
global messagewindow
messagewindow = Toplevel()
# Covers whole screen to come out press Alt + Esc
messagewindow.wm_attributes("-fullscreen", 1)
messagewindow.title("Notification Screen")
tt = '{:3}'.format(str(i[0])) + ' {:15}'.format(str(i[1])) + ' {:15}'.format(
str(i[2])) + ' {:15}'.format(str(i[3])) + '\n'
msg = 'YOUR LECTURE/PRAC DETAILS \n\n'+" "+tt
# to place message at centre
msgflash = Label(messagewindow, text=msg, bg="#1f618d",fg='white', font=("Verdana", 28,'bold'),height=5,relief = RAISED)
msgflash.place(x=250, y=300)
#Bell rings ___________________________________________________________________________________________
pygame.init()
pygame.mixer.init()
sounda = pygame.mixer.Sound("bell.wav")
sounda.play()
time.sleep(5)
#Belll rings____________________________________________________________________________________________
messagewindow.after(5000, messagewindow.withdraw)
# schedule closing of showMesagewin event in 5 seconds
messagewindow.mainloop()
currentDT = datetime.datetime.now()
t=currentDT.strftime("%H")
conn = sq.connect("Teacher.db")
curr = conn.cursor()
tid = __userip.get()
day2 = datetime.datetime.now()
day3 = day2.strftime("%A")
curr.execute("select Time,Subject,Lecture_prac,Venue from "+day3+" where Teacher_ID=?", (tid,))
sc = curr.fetchall()
t1=0
for i in sc:
if (t == i[0]):
alertmsg()
print ('gbhj')
showMesagewin()
newteacheradd.after(1000,repeatedquery)
#-------------------------------------------------------------------------------------------------
repeatedquery()
Edited Code
#repeatedly checking if system time matched any teachers scedule time--------------------------------
from tkinter import *
import datetime
import time
def mainwin():
newteacherappend=Tk()
i=[]
i.append(2)
i.append('Phy')
i.append('L')
i.append('301')
def repeatedquery():
def alertmsg():
for j in range (4):
newteacherappend.withdraw()
messagewindow = Toplevel()
# Covers whole screen to come out press Alt + Esc
messagewindow.wm_attributes("-fullscreen", 1)
messagewindow.title("Notification")
msgflash = Label(messagewindow, text='Notice', bg="#1f618d", fg='white', font=("Verdana", 28, 'bold'),
height=5,width=40, relief=RAISED)
msgflash.place(x=150, y=300)
print ("hjgj")
time.sleep(5)
messagewindow.after(5000, messagewindow.withdraw)
messagewindow.mainloop()
def showMesagewin():
newteacherappend.withdraw()
global messagewindow
messagewindow = Toplevel()
# Covers whole screen to come out press Alt + Esc
messagewindow.wm_attributes("-fullscreen", 1)
messagewindow.title("Notification Screen")
tt = '{:3}'.format(str(i[0])) + ' {:15}'.format(str(i[1])) + ' {:15}'.format(
str(i[2])) + ' {:15}'.format(str(i[3])) + '\n'
msg = 'YOUR LECTURE/PRAC DETAILS \n\n'+" "+tt
# to place message at centre
msgflash = Label(messagewindow, text=msg, bg="#1f618d",fg='white', font=("Verdana", 28,'bold'),height=5,relief = RAISED)
msgflash.place(x=250, y=300)
messagewindow.after(5000, messagewindow.withdraw)
# schedule closing of showMesagewin event in 5 seconds
messagewindow.mainloop()
currentDT = datetime.datetime.now()
t=currentDT.strftime("%H")
t=2
if (t == i[0]):
alertmsg()
print ('gbhj')
showMesagewin()
newteacherappend.after(1000,repeatedquery)
repeatedquery()
newteacherappend.mainloop()
mainwin()
I made code which use after without sleep to display flashing messages - first after after 5 seconds, second after 15 second. And it has only one mainloop().
More information in code
import tkinter as tk
import datetime
# --- functions ----
# function which creates window with message
def message_start(text):
global repeates
global message_window
global message_label
repeates = 3 # how many times change background color
# create window with messages
message_window = tk.Toplevel()
message_label = tk.Label(message_window, text=text, bg='red')
message_label.pack()
# update window after 500ms
root.after(500, message_update)
# function which changes background in displayed window
def message_update():
global message_window
global repeates
if repeates > 0:
repeates -= 1
if message_label['bg'] == 'red':
message_label['bg'] = 'green'
else:
message_label['bg'] = 'red'
# update window after 500ms
root.after(500, message_update)
else:
# close window
message_window.destroy()
# inform `check_time` that window is not busy
message_window = None
# loop which updates current time and checks which message it has to display
def check_time():
# display current time
current_time = datetime.datetime.now()
root_label_time['text'] = current_time.strftime('%Y.%m.%d %H:%M:%S')
# check if there is message to display
for message in messages:
if current_time >= message['start']: # it is time to display message
if message['state'] == 'waiting': # message is not displayed at this moment
if message_window is None: # window is not busy
message['state'] = 'displayed' # don't display it again
message_start(message['text']) # display message
# update time after 1000ms (1s)
root.after(1000, check_time)
# --- main ---
messages = [
{
'text': 'Time for coffee',
'start': datetime.datetime.now() + datetime.timedelta(seconds=5),
'state': 'waiting',
},
{
'text': 'Back to work',
'start': datetime.datetime.now() + datetime.timedelta(seconds=15),
'state': 'waiting',
},
]
message_window = None
repeates = 3
# ---
root = tk.Tk()
# label with current time
root_label_time = tk.Label(root, text='- wait -')
root_label_time.pack()
# label with sheduler
root_label_sheduler = tk.Label(root)
root_label_sheduler.pack()
# displa messages in sheduler
for message in messages:
root_label_sheduler['text'] += "\n" + message['start'].strftime('%Y.%m.%d %H:%M:%S ') + message['text']
# start displaying time
check_time()
root.mainloop()

How to make timer/program open only after pressing key instead of immediately?

I need to make this clock open only after pressing a key, lets say "t". Now it opens immediately after running it.
import tkinter as tk
def update_timeText():
if (state):
global timer
timer[2] += 1
if (timer[2] >= 100):
timer[2] = 0
timer[1] += 1
if (timer[1] >= 60):
timer[0] += 1
timer[1] = 0
timeString = pattern.format(timer[0], timer[1], timer[2])
timeText.configure(text=timeString)
root.after(10, update_timeText)
def start():
global state
state=True
state = False
root = tk.Tk()
root.wm_title('Simple Kitchen Timer Example')
timer = [0, 0, 0]
pattern = '{0:02d}:{1:02d}:{2:02d}'
timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 50))
timeText.pack()
startButton = tk.Button(root, text='Start', command=start)
startButton.pack()
update_timeText()
root.mainloop()
It is in another program so as I have my graphics window I will press "t" and the clock will open.
Keyboard is a python module that can detect keystrokes. Install it by doing this command.
pip install keyboard
Now you can do this.
while True:
try:
if keyboard.is_pressed('t'):
state = True
elif(state != True):
pass
except:
state = False
break #a key other than t the loop will break
I would recommend you to organize the code little bit, like class structure. One possible implementation would be like that:
import tkinter as tk
TIMER = [0, 0, 0]
PATTERN = '{0:02d}:{1:02d}:{2:02d}'
class Timer:
def __init__(self, master):
#I init some variables
self.master = master
self.state = False
self.startButton = tk.Button(root, text='Start', command=lambda: self.start())
self.startButton.pack()
self.timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 50))
self.timeText.pack()
def start(self):
self.state = True
self.update_timeText()
def update_timeText(self):
if (self.state):
global TIMER
TIMER[2] += 1
if (TIMER[2] >= 100):
TIMER[2] = 0
TIMER[1] += 1
if (TIMER[1] >= 60):
TIMER[0] += 1
TIMER[1] = 0
timeString = PATTERN.format(TIMER[0], TIMER[1], TIMER[2])
self.timeText.configure(text=timeString)
self.master.after(10, self.update_timeText)
if __name__ == '__main__':
root = tk.Tk()
root.geometry("900x600")
root.title("Simple Kitchen Timer Example")
graph_class_object = Timer(master=root)
root.mainloop()
So clock will start when you click to button. If you want to start the clock by pressing "t" in keyboard, you need to bind that key to your function.
You can also add functionality if you want to stop the clock when you click to the button one more time.
EDIT:
if you also want to start to display the clock by clicking the button, you can move the code for initializing the label in to start function.
def start(self):
self.state = True
self.timeText = tk.Label(root, text="00:00:00", font=("Helvetica", 50))
self.timeText.pack()
self.update_timeText()

Categories

Resources