class pomodoro(): def __init__(self): self.path = Path(__file__).parent.absolute( ) #Get the absolute path to the directory of the current file self.toaster = ToastNotifier() self.window = Tk() self.timer = [ 0, 0 ] #List for keeping and calculating minutes and seconds (timer [0] - minutes, timer [1] - seconds) self.pomodorocount = 0 #Variable for storing performed pomodoros self.status = 1 #Variable for determining the state (0 - work, 1 - short break, 2 - long break) self.after_id = 0 #Variable to storing the identifier of the after method (to stop the timer, we will transmit this identifier to the after_cancel method) self.timestr = str(self.timer[0]) + ':' + str( self.timer[1]) #Variable type str to update label_time self.window.title('Pomodoro Timer') self.window.geometry('400x400') self.label_work = Label(text='Pomodoro') self.frame_work = Frame() #Used to group widgets self.entry_m_work = Entry(self.frame_work, width=5) self.entry_s_work = Entry(self.frame_work, width=5) text = '25' self.entry_m_work.insert( 0, text) #We prescribe the initial values in the input field text = '0' self.entry_s_work.insert(0, text) self.label_relax = Label(text='Short break') self.frame_relax = Frame() self.entry_m_relax = Entry(self.frame_relax, width=5) self.entry_s_relax = Entry(self.frame_relax, width=5) text = '5' self.entry_m_relax.insert(0, text) text = '0' self.entry_s_relax.insert(0, text) self.label_longrelax = Label(text='Long break') self.frame_longrelax = Frame() self.entry_m_longrelax = Entry(self.frame_longrelax, width=5) self.entry_s_longrelax = Entry(self.frame_longrelax, width=5) text = '30' self.entry_m_longrelax.insert(0, text) text = '0' self.entry_s_longrelax.insert(0, text) self.label_infopomodoro = Label(text='Number of pomodoros: {}'.format( self.pomodorocount), font=("Times", 20)) self.label_infostatus = Label(text='Get started!', fg="blue", font=("Times", 20)) self.label_time = Label(text='0:0', font=("Area", 100)) self.frame_button = Frame() self.button_start = Button(self.frame_button, width=5, text='Start', command=self.start) self.button_reset = Button(self.frame_button, width=5, text='Reset', command=self.reset, state='disabled') def pack(self): #Use the pack method for widgets in this function self.label_work.pack() self.frame_work.pack() self.entry_m_work.pack(side=LEFT) self.entry_s_work.pack(side=LEFT) self.label_relax.pack() self.frame_relax.pack() self.entry_m_relax.pack(side=LEFT) self.entry_s_relax.pack(side=LEFT) self.label_longrelax.pack() self.frame_longrelax.pack() self.entry_m_longrelax.pack(side=LEFT) self.entry_s_longrelax.pack(side=LEFT) self.label_infopomodoro.pack() self.label_infostatus.pack() self.label_time.pack() self.frame_button.pack() self.button_start.pack(side=LEFT) self.button_reset.pack(side=LEFT) def start(self): #The function is called by pressing the Start button self.button_start.configure(state='disabled') self.button_reset.configure(state='active') self.status_check() def tick(self): #Timer update function self.timer[1] -= 1 #We subtract one second if self.timer[1] == -1: #When the value becomes -1: self.timer[1] = 59 #Set the value of seconds in 59 self.timer[0] -= 1 #We subtract one minute self.timestr = str(self.timer[0]) + ':' + str( self.timer[1] ) #We combine values from the list to the timestr variable in the form of 0:0 self.label_time.configure(text=self.timestr) #We update the label self.status_check() #Call the check function def status_check(self): #Status check function (work or break) if self.timestr == '0:0': #Checking whether the timer time ended if self.status == 0: #If you work self.pomodorocount += 1 #Add 1 to performed pomodoros self.label_infopomodoro.configure( text='Number of pomodoros: {}'.format(self.pomodorocount), font=("Times", 20)) #We update the label if self.pomodorocount % 4 == 0: #If the number of pomodoros is multiple 4 self.status = 2 #We update status in 2 (long break) self.status_change() #Call the status change function else: self.status = 1 #We update status in 1 (short break) self.status_change() #Call the status change function elif self.status == 1 or self.status == 2: #If we break self.status = 0 #We update status in 0 (work) self.status_change() #Call the status change function else: self.after_id = self.label_time.after( 1000, self.tick ) #If the time did not end, call the after method to execute the tick function every second def status_change(self): #Status change function (check the value in the status variable) if self.status == 0: #Work #Show notification + we prescribe an absolute path to the timer.ico icon (due to lying next to the current file) self.toaster.show_toast("Pomodoro Timer", "Time for work!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure( text='Time for work!', fg="red", font=("Times", 20)) #We update the label with the status self.timer[0] = int(self.entry_m_work.get( )) #Record the values of the input fields to the timer list self.timer[1] = int(self.entry_s_work.get()) elif self.status == 1: #Short break self.toaster.show_toast("Pomodoro Timer", "Time for short break!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure(text='Time for short break!', fg="green", font=("Times", 20)) self.timer[0] = int(self.entry_m_relax.get()) self.timer[1] = int(self.entry_s_relax.get()) elif self.status == 2: #Long break self.toaster.show_toast("Pomodoro Timer", "Time for long break!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure(text='Time for long break!', fg="lime", font=("Times", 20)) self.timer[0] = int(self.entry_m_longrelax.get()) self.timer[1] = int(self.entry_s_longrelax.get()) if self.timer[ 1] > 60: #If in the input field of seconds it was a value of more than 60, then set the value of 60 self.timer[1] = 60 if self.timer[ 1] == 0: #If there was zero in the input field in the input field, then we subtract out of 1 minutes and set the value of seconds in 60 self.timer[0] -= 1 self.timer[1] = 60 self.after_id = self.label_time.after( 1000, self.tick ) #Call an after method for executing the tick function every second def reset(self): #Timer restart function - set the initial values of variables, update labels and buttons self.button_reset.configure(state='disabled') self.label_time.after_cancel( self.after_id) #Stop the timer for the after identifier self.timer = [0, 0] self.pomodorocount = 0 self.status = 1 self.after_id = 0 self.timestr = str(self.timer[0]) + ':' + str(self.timer[1]) self.label_time.configure(text=self.timestr) self.button_start.configure(state='active') self.label_infopomodoro.configure( text='Number of pomodoros: {}'.format(self.pomodorocount), font=("Times", 20)) self.label_infostatus.configure(text='Get started!', fg="blue", font=("Times", 20)) def mainloop(self): self.window.mainloop()
class SectionUne(Frame): """ """ def __init__(self, master, controller): Frame.__init__(self, master) self._controller = controller def nouvelle_partie(self): """ """ _np = Bouton(self, "Nouvelle partie", self._controller.relance_nouvelle_partie) _np.fixer_des_options(font=("Helvetica", 20), padx=2, pady=5) _np.grid(row=0, column=0, padx=5, pady=5) def valeur_N(self, n): """ """ self._n = StringVar() Label(self, textvariable=self._n, font=("Helvetica", 20, "bold"), bd=1, relief="groove", padx=30, pady=5).grid(row=0, column=1, padx=150) self._n.set(n) def update_label_n(self, n): """ Met à jour la nouvelle valeur à trouver """ self._n.set(n) def bouton_solution(self): """ """ _b = Bouton(self, "Solution", self._controller.generer_solution) _b.fixer_des_options(font=("Helvetica", 20), padx=5, pady=5, borderwidth=2, background="#3CB371", fg="white", activebackground="#2E8B57", activeforeground="white") _b.grid(row=0, column=3, padx=5, pady=5) def bouton_stop(self): """ """ self._btn = Bouton(self, "Stop", self._controller.stop_compte_a_rebours) self._btn.fixer_des_options(font=("Helvetica", 20), padx=5, pady=5, borderwidth=2, background="#273746", fg="white", activebackground="#273746", activeforeground="white") self._btn.grid(row=0, column=3, padx=5, pady=5) def desactiver_btn_stop(self): self._btn.fixer_des_options(state="disable") def label_compte_a_rebours(self, temps=45): """ """ self._label_compte = Label(self, text="45 secondes") self._label_compte.config(font=("Helvetica", 10), padx=2, pady=5) self._label_compte.grid(row=0, column=0, padx=5, pady=5) self._id = None self._label_compte.after( 1000, lambda: self._controller.compte_a_rebours( self._label_compte, temps, self._id)) def stop_compte_a_rebours(self): self._label_compte.after_cancel(self._id) @property def get_temps(self): return self._temps
class Clock(Tk): def __init__(self): super().__init__() self.title("Timer") self.counter = 28800 self.running = False self.counting_id = None self.default_display = "00:00:00" self.on_top = False self.geometry("+800+300") self.attributes("-alpha", 0.9) self.timer_frame = LabelFrame(self, text="Timer") self.timer_frame.grid(row=0, column=0, padx=[20, 0], pady=10) self.timer_label = Label(self.timer_frame, text=self.default_display, font=("Helvetica 20")) self.timer_label.grid(row=0, column=0, columnspan=3) self.start_button = Button( self.timer_frame, text="Start", command=self.start_timer, ) self.start_button.grid(row=1, column=0) self.pause_button = Button(self.timer_frame, text="Pause", command=self.pause_timer) self.pause_button.grid(row=1, column=1) self.reset_button = Button(self.timer_frame, text="Reset", command=self.reset_timer) self.reset_button.grid(row=1, column=2) self.opacity_frame = LabelFrame(self, text="Opacity") self.opacity_frame.grid(row=0, column=1, padx=20) self.decrease_opacity_button = Button( self.opacity_frame, text="-", width=2, font=("Helvetica 12"), command=self.decrease_opacity, ) self.decrease_opacity_button.grid(row=0, column=0, padx=[10, 0]) self.increase_opacity_button = Button( self.opacity_frame, text="+", width=2, font=("Helvetica 12"), command=self.increase_opacity, ) self.increase_opacity_button.grid(row=0, column=1, padx=[0, 10]) self.on_top_button = Button(self.opacity_frame, text="Always On Top", command=self.always_on_top) self.on_top_button.grid(row=1, column=0, columnspan=2, pady=[5, 0]) def counting(self): """Timer functionality.""" if self.running: timer_timestamp = datetime.fromtimestamp(self.counter) label_text = timer_timestamp.strftime("%H:%M:%S") self.timer_label.config(text=label_text) self.counter += 1 self.counting_id = self.timer_label.after(1000, self.counting) def start_timer(self): """Start and display the timer.""" self.running = True self.counting() self.start_button["state"] = "disabled" self.pause_button["state"] = "normal" self.reset_button["state"] = "normal" def pause_timer(self): """Pause and display the timer.""" self.running = False self.timer_label.after_cancel(self.counting_id) self.counter -= 1 self.start_button["state"] = "normal" self.pause_button["state"] = "disabled" self.reset_button["state"] = "normal" def reset_timer(self): """Reset and display the timer.""" self.running = False self.counter = 28800 self.timer_label.after_cancel(self.counting_id) self.timer_label.config(text=self.default_display) self.start_button["state"] = "normal" self.pause_button["state"] = "disabled" self.reset_button["state"] = "disabled" def increase_opacity(self): """Increase the opacity of the app.""" self.decrease_opacity_button["state"] = "normal" opacity = self.attributes()[1] if opacity >= 1: self.increase_opacity_button["state"] = "disabled" else: self.attributes("-alpha", opacity + 0.1) def decrease_opacity(self): """Decrease the opacity of the app.""" self.increase_opacity_button["state"] = "normal" opacity = self.attributes()[1] if opacity <= 0.2: self.attributes("-alpha", 0.1) self.decrease_opacity_button["state"] = "disabled" else: self.attributes("-alpha", opacity - 0.1) def always_on_top(self): if self.on_top == False: self.on_top = True self.attributes("-topmost", True) self.on_top_button.config(fg="red") else: self.on_top = False self.attributes("-topmost", False) self.on_top_button.config(fg="black")
class pomodoro(): def __init__(self): self.path = Path(__file__).parent.absolute( ) #Получаем абсолютный путь к директории текущего файла self.toaster = ToastNotifier() self.window = Tk() self.timer = [ 0, 0 ] #Список для хранения и вычисления значений минут и секунд (timer[0] - минуты, timer[1] - секунды) self.pomodorocount = 0 #Переменная для хранения выполненных помидоров self.status = 1 #Переменная для определения состояния (0 - работа, 1 - короткий отдых, 2 - длинный отдых) self.after_id = 0 #Переменная для хранения идентификатора метода after (Для остановки таймера будем передавать этот идентификатор в метод after_cancel) self.timestr = str(self.timer[0]) + ':' + str( self.timer[1] ) #Переменная типа str для обновления метки с таймером self.window.title('Pomodoro Timer') self.window.geometry('400x400') self.label_work = Label(text='Время работы') self.frame_work = Frame() #Используется для группировки виджетов self.entry_m_work = Entry(self.frame_work, width=5) self.entry_s_work = Entry(self.frame_work, width=5) text = '25' self.entry_m_work.insert( 0, text) #Прописываем начальные значения в поле ввода text = '0' self.entry_s_work.insert(0, text) self.label_relax = Label(text='Время отдыха') self.frame_relax = Frame() self.entry_m_relax = Entry(self.frame_relax, width=5) self.entry_s_relax = Entry(self.frame_relax, width=5) text = '5' self.entry_m_relax.insert(0, text) text = '0' self.entry_s_relax.insert(0, text) self.label_longrelax = Label(text='Время длинного отдыха') self.frame_longrelax = Frame() self.entry_m_longrelax = Entry(self.frame_longrelax, width=5) self.entry_s_longrelax = Entry(self.frame_longrelax, width=5) text = '30' self.entry_m_longrelax.insert(0, text) text = '0' self.entry_s_longrelax.insert(0, text) self.label_infopomodoro = Label(text='Выполнено помидоров: {}'.format( self.pomodorocount), font=("Times", 20)) self.label_infostatus = Label(text='Начните работу!', fg="blue", font=("Times", 20)) self.label_time = Label(text='0:0', font=("Area", 100)) self.frame_button = Frame() self.button_start = Button(self.frame_button, width=5, text='Старт', command=self.start) self.button_reset = Button(self.frame_button, width=10, text='Перезапуск', command=self.reset, state='disabled') def pack(self): #Используем метод pack для виджетов в этой функции self.label_work.pack() self.frame_work.pack() self.entry_m_work.pack(side=LEFT) self.entry_s_work.pack(side=LEFT) self.label_relax.pack() self.frame_relax.pack() self.entry_m_relax.pack(side=LEFT) self.entry_s_relax.pack(side=LEFT) self.label_longrelax.pack() self.frame_longrelax.pack() self.entry_m_longrelax.pack(side=LEFT) self.entry_s_longrelax.pack(side=LEFT) self.label_infopomodoro.pack() self.label_infostatus.pack() self.label_time.pack() self.frame_button.pack() self.button_start.pack(side=LEFT) self.button_reset.pack(side=LEFT) def start(self): #Функция вызывается при нажатии кнопки Start self.button_start.configure(state='disabled') self.button_reset.configure(state='active') self.status_check() def tick(self): #Функция для обновления таймера self.timer[1] -= 1 #Вычитаем одну секунду if self.timer[1] == -1: #Когда значение становится -1: self.timer[1] = 59 #Устанавливаем значение секунд в 59 self.timer[0] -= 1 #Вычитаем одну минуту self.timestr = str(self.timer[0]) + ':' + str( self.timer[1] ) #Объединяем значения из списка в переменную timestr в виде 0:0 self.label_time.configure(text=self.timestr) #Обновляем метку self.status_check() #Вызываем функцию проверки def status_check(self): #Функция проверки статуса (работаем или отдыхаем) if self.timestr == '0:0': #Проверяем закончилось ли время таймера if self.status == 0: #Если работаем self.pomodorocount += 1 #Прибавляем 1 к выполненным помидорам self.label_infopomodoro.configure( text='Выполнено помидоров: {}'.format(self.pomodorocount), font=("Times", 20)) #Обновляем метку if self.pomodorocount % 4 == 0: #Если кол-во помидоров кратно 4 self.status = 2 #Обновляем статус в 2 (длинный отдых) self.status_change() #Вызываем функцию изменения статуса else: self.status = 1 #Обновляем статус в 1 (короткий отдых) self.status_change() #Вызываем функцию изменения статуса elif self.status == 1 or self.status == 2: #Если отдыхаем self.status = 0 #Обновляем статус в 0 (работа) self.status_change() #Вызываем функцию изменения статуса else: self.after_id = self.label_time.after( 1000, self.tick ) #Если время не кончилось, вызываем метод after для выполнения функции tick каждую секунду def status_change(self): #Функция изменения статуса (проверяем значение в переменной status) if self.status == 0: #Работа #Показываем уведомление + прописываем абсолютный путь к иконке timer.ico (должная лежать рядом с текущим файлом) self.toaster.show_toast("Pomodoro Timer", "Время работы!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure( text='Время работы!', fg="red", font=("Times", 20)) #Обновляем метку со статусом self.timer[0] = int(self.entry_m_work.get( )) #Записываем значения полей ввода в список timer self.timer[1] = int(self.entry_s_work.get()) elif self.status == 1: #Короткий отдых self.toaster.show_toast("Pomodoro Timer", "Время отдыха!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure(text='Время отдыха!', fg="green", font=("Times", 20)) self.timer[0] = int(self.entry_m_relax.get()) self.timer[1] = int(self.entry_s_relax.get()) elif self.status == 2: #Длинный отдых self.toaster.show_toast("Pomodoro Timer", "Время длинного отдыха!", threaded=True, icon_path='{}\\timer.ico'.format( self.path)) self.label_infostatus.configure(text='Время длинного отдыха!', fg="lime", font=("Times", 20)) self.timer[0] = int(self.entry_m_longrelax.get()) self.timer[1] = int(self.entry_s_longrelax.get()) if self.timer[ 1] > 60: #Если в поле ввода секунд было значение больше 60, то выставляем значение 60 self.timer[1] = 60 if self.timer[ 1] == 0: #Если в поле ввода секунд был ноль, то вычитаем из минут 1 и выставляем значение секунд в 60 self.timer[0] -= 1 self.timer[1] = 60 self.after_id = self.label_time.after( 1000, self.tick ) #Вызываем метод after для выполнения функции tick каждую секунду def reset(self): #Функция перезапука таймера - выставляем начальные значения переменных, обновляем метки и кнопки self.button_reset.configure(state='disabled') self.label_time.after_cancel( self.after_id) #Остановка таймера по идентификатору after self.timer = [0, 0] self.pomodorocount = 0 self.status = 1 self.after_id = 0 self.timestr = str(self.timer[0]) + ':' + str(self.timer[1]) self.label_time.configure(text=self.timestr) self.button_start.configure(state='active') self.label_infopomodoro.configure( text='Выполнено помидоров: {}'.format(self.pomodorocount), font=("Times", 20)) self.label_infostatus.configure(text='Начните работу!', fg="blue", font=("Times", 20)) def mainloop(self): self.window.mainloop()