Reaction Time Game counting rong (Python 3.10) - python

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.

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.

How do I get this timer to count down properly?

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

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

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

Tkinter show processing message

In my new program, the user gives a non-negative integer number to the program in order to calculate the factorial of this number. But sometimes when the number is large, like 25637, it takes some time to calculate. I want if this time is over than 2 seconds to print a processing message to the Python's shell. Unfortunately I am a new guy to tkinter and I don't know how to do that.
Please can you show me the solution of that I ask in my code in order to understand it?
This is my code:
#! usr/bin/python
# Filename: x_Factorial!_GUI.py
import sys, warnings
if sys.version_info[0] < 3:
warnings.warn("System FAILURE, Python 3.x is required in order to execute this program",
RuntimeWarning)
else:
version_info_num = str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2])
print("System SUCCESS, You are currently executing this program on Python's version: {}".format(version_info_num))
import tkinter as tk
from tkinter import ttk
class GUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
#Window_Creation
scr_xloc = int(self.winfo_screenwidth() / 2 - 800 / 2)
scr_yloc = int(self.winfo_screenheight() / 2 - 600 / 2 - 30)
self.geometry("800x600+{}+{}".format(scr_xloc, scr_yloc))
self.minsize(width = 800, height = 600)
self.title("x_Factorial!")
self.configure(bg = "#F06428")
#Window_Controls
self.bind("<Configure>", self.Resize_Window)
self.bind("<F11>", self.Toggle_Fullscreen)
self.state_mode = False
self.bind("<Escape>", self.Quit)
# Widgets_Creation
self.User_Line_Text = tk.StringVar()
self.User_Line_Text.set("Please enter a non-negative integer number:")
self.User_Line = tk.Entry(bg = "#FFFFFF", font = ("Comic Sans MS", 10, "bold"), fg = "#000000",
justify = "left", relief = "flat", textvariable = self.User_Line_Text)
self.User_Line.place(width = 400, height = 40, x = 200, y = 250)
self.User_Line.bind("<Button-1>", self.Clear_Text)
self.User_Line.bind("<Key-Return>", self.Processing)
self.Output_Box = tk.Text(bg = "#FFFFFF", font = ("Comic Sans MS", 10, "bold"), fg = "#000000",
relief = "flat")
self.Output_Box.place(width = 600, height = 240, x = 100, y = 320)
def Clear_Text(self, event):
self.User_Line.delete("insert", "end")
def Processing(self, event):
user_input = str(self.User_Line.get())
user_input = int(float(user_input))
import math
factorial_num = math.factorial(user_input)
self.Output_Box.delete("1.0", "end")
self.Output_Box.insert("1.0", str(user_input) + "! = " + str(factorial_num))
def Resize_Window(self, event):
self.win_width = int(event.width)
self.win_height = int(event.height)
def Toggle_Fullscreen(self, event):
self.state_mode = not self.state_mode
self.attributes("-fullscreen", self.state_mode)
def Quit(self, event):
self.destroy()
if __name__ == "__main__":
App = GUI()
App.mainloop()
The simpler way is to print the processing message just before the call to factorial -- maybe something like:
print('calculating factorial of %d. . . ' % user_input, end='')
and once you have the answer:
print(factorial_num)
However, this will always print.
If you only want to print after two seconds have elapsed then you will need to start a timer thread, have it print after two seconds, or signal it to abort instead if you get your answer back first. Something like:
from threading import Thread
import time
class Timer(Thread):
abort = False
def run(self):
time.sleep(2)
if not self.abort:
print('Processing...')
and then around the math.factorial call:
timer = Timer()
timer.start()
factorial_num = math.factorial(user_input)
timer.abort = True
Unfortunately, time.sleep is not guaranteed to wake up exactly after two seconds, and on my system in doesn't wake up until after the math.factorial call is complete, making it useless for me.
Edit
A little more debugging and I discovered the problem is not the math.factorial function -- it can calculate 173,000 in about two seconds on my 5-year-old i7. The problem is trying to get that number as text in the tkinter window, which is 831,053 digits long (and took 46 seconds to popuulate).

Categories

Resources