Часы в python tkinter

how to make a digital clock in python

The Original article can be found on kalebujordan.dev Hi guys, In this article, I’m going to share with you how to build a digital clock using Python programming in just a few lines of code using the Tkinter and Time module.

Requirements

If you’re on window OS you don’t really need to install anything since our simple digital clock app will be using only built-in modules time and Tkinter But if you’re running Linux OS most of the time pre installed python interpreter doesn’t come with the Tkinter installed, therefore you might need to install it manually just as shown below;

Installation

sudo apt-get install python3-tk 

Let’s get started .

The idea is really simple, firstly we will create an empty window using the Tkinter, then we gonna configure and place a Label widget within our empty window, and then finally we will be updating the value of the label to be the current time after every 0.08s.

Читайте также:  Php ini что включать

getting current time .

Time module provides a variety of ways of getting time, In this article, we are going to use* strftime() to parse the current time into the *Hour: Minutes: Seconds format.

Example of usage
>>import time >>time.strftime('%H:%M:%S') '18:10:53' 

Now lets add graphical interface

Previous experience with the Tkinter library would be an advantage for you, but even if this is your first time still you can make it, the syntax is intuitive and straight forward.

Making empty window with tkinter

In making an empty clock window, we gonna use geometry () to specify the dimension of the displayed window, and at the end put mainloop() to prevent the displayable window from exiting immediately.

from tkinter import Label, Tk #======= Configuring window ========= window = Tk() window.title("digital clock") window.geometry("200x200") window.resizable(False, False) #============ Logic lives here ======= window.mainloop() 

Alt Text

When you run the above code, it will produce an interface like this;

Adding some logic to our code ..

Now that we have our empty window, let’s now add a label to place our time information together with a function to update the value on the label every 80 milliseconds.

clock_label = Label(window, bg="green", fg="white", font = ("Times", 30), relief='flat') clock_label.place(x = 20, y = 20) def update_label(): current_time = strftime('%H: %M: %S') clock_label.configure(text = current_time) clock_label.after(80, update_label) update_label() 
why 80 milliseconds?

According to research human brain can only process 12 separate images per second, anything more than that it will be perceived as a single picture, this is what causes the illusion of motion. Below is the full code of our digital clock, with you, can try changing the code parameter the way you would like and then press run again.

from time import strftime from tkinter import Label, Tk #======= Configuring window ========= window = Tk() window.title("") window.geometry("200x80") window.configure(bg="green") window.resizable(False, False) clock_label = Label(window, bg="green", fg="white", font = ("Times", 30, 'bold'), relief='flat') clock_label.place(x = 20, y = 20) def update_label(): current_time = strftime('%H: %M: %S') clock_label.configure(text = current_time) clock_label.after(80, update_label) update_label() window.mainloop() 

Alt Text

Once you run the above lines of code, you should be seeing a widget with clock details rendered on your machine similar to that screenshot below; Based on your interest I recommend you to also check these;

  • How to make a music player in python
  • How to track phone number in Python
  • How to make a python GUI calculator in Python
  • How to make a guessing game in Python
  • How to program Arduino board with Python
  • How to build a website blocker in Python

Kalebu / Digital-clock-in-Python

A digital clock application made with python and tkinter

Digital-clock-in-Python

Intro

This is a code for a simple digital clock made in python with help of the time module and Tkinter library

How to run

Firstly download or clone this repo and then move into the project folder as shown below;

$-> git clone https://github.com/Kalebu/Digital-clock-in-Python $-> cd Digital-clock-in-Python $ Digital-clock-in-Python -> python app.py

Output

Once you run the code, it will render the output similar to what shown below;

digital_clock

This code is the continuation of a series of Python tutorial published on my blog, and the full article with code for can be found on Make a Digital Clock

Give it a star 🎉

Did you find this information useful, then give it a star

Credits

Источник

Цифровые часы с Python и Tkinter

Цифровые часы с Python и Tkinter

Здравствуйте! В сегодняшней статье мы рассмотрим, как создать цифровые часы при помощи Python и Tkinter. Также нам понадобится модуль time. Мы создадим окно, затем добавим к нему метку Lable, в которой будут отображаться цифровые знаки, обновляющиеся по логике часов. Так мы будем имитировать изменение времени. И так, приступим.

Создадим файл в Pycharm или любом другом редакторе и придадим ему расширение .py.

# Для начала импортируем все элементы из модуля

# импорт модуля для преобразования кортежей через format
from time import strftime

# создание экземпляра класса Tk(), для отображенния окна приложения
root = Tk()
# добавление заголовка к окну
root.title(‘Цифровые часы’)

# создание текстовой метки в окне прилржения, для отображения цифровых знаков. Цифры будут белыми на черном фоне
lable = Label(root, font=(‘aerial’, 30), background=’black’, foreground=’white’)

# функция отображения времени
def time():
string = strftime(‘%H:%M:%S %p’)
lable.config(text=string)
lable.after(1000, time)

# азмещение метки времени по центру
lable.pack(anchor=’center’)
time()

# запуск цикла программы
mainloop()

Если все сделано правильно, на экране отобразится текущее время с компьютера. Таким образом, мы создали цифровые часы с Python и графической библиотекой Tkinter.

Создано 27.10.2022 12:37:46

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Пишем GUI часы на Python tkinter

    Пишем GUI часы на Python tkinter

    Статьи

    Введение

    В ходе статьи напишем GUI часы на языке программирования Python с использованием модуля tkinter.

    Написание кода GUI часов

    Для начала импортируем модуль time и tkinter:

    import time from tkinter import *

    Далее создадим окно, добавим заголовок “Часы” и запретим возможность изменять размеры окна:

    import time from tkinter import * root = Tk() root.title('Часы') root.resizable(0, 0) root.mainloop()

    Создадим виджет Label(), расположим его на окне root, шрифт укажем Arial 70 размера и отобразим методом pack():

    import time from tkinter import * root = Tk() root.title('Часы') root.resizable(0, 0) watch = Label(root, font="Arial 70") watch.pack() root.mainloop()

    Теперь создадим функцию, которую назовём tick(). Внутри неё будет устанавливаться нынешнее время в Label(), а благодаря методу after() раз в секунду функцию будет вызываться рекурсивно:

    import time from tkinter import * def tick(): watch['text'] = time.strftime("%H:%M:%S") watch.after(1000, tick) root = Tk() root.title('Часы') root.resizable(0, 0) watch = Label(root, font="Arial 70") watch.pack() root.mainloop()

    Итоговый результат

    Заключение

    В ходе статьи мы с Вами написали код GUI часов на языке программирования Python. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

    Источник

    Цифровые часы в Python с использованием 2 простых модулей

    Во-первых, нам нужно установить модуль Tkinter. Если у вас нет этого модуля, уже установленного в вашей системе, вы можете установить то же самое, используя диспетчер пакетов PIP Package:

    C:\Users\Admin>pip install tkinter

    После того, как ваш модуль Tkinter успешно установлен в вашей системе, вы хотите пойти.

    Кодирование цифровых часов в Python

    Мы будем использовать модуль TKinter и модуль времени, чтобы построить наши часы сегодня.

    1. Модуль Tkinter.

    Tkinter – это стандартная библиотека GUI для Python. Tkinter получает свое название от интерфейса TK. Когда Python сочетается с TKinter, он обеспечивает быстрый и простой способ создания приложений GUI. TKINTER предоставляет мощный объектно-ориентированный интерфейс для TK GUI Toolkit. Tkinter – это привязка Python с TK GUI Toolkit.

    2. Время модуля

    Время модуля предоставляет множество способов получения времени, в этой статье мы собираемся использовать strftime () Чтобы разбирать текущее время в час: минуты: в секунду формата.

    3. Реализация цифровых часов

    В этом коде мы будем использовать Геометрия () Чтобы указать размер отображаемого окна, и мы будем использовать mainloop () Чтобы предотвратить быстрое окно в окне.

    #import all the required libraries first import sys from tkinter import * #import time library to obtain current time import time #create a function timing and variable current_time def timing(): #display current hour,minute,seconds current_time = time.strftime("%H : %M : %S") #configure the clock clock.config(text=current_time) #clock will change after every 200 microseconds clock.after(200,timing) #Create a variable that will store our tkinter window root=Tk() #define size of the window root.geometry("600x300") #create a variable clock and store label #First label will show time, second label will show hour:minute:second, third label will show the top digital clock clock=Label(root,font=("times",60,"bold"),bg="blue") clock.grid(row=2,column=2,pady=25,padx=100) timing() #create a variable for digital clock digital=Label(root,text="AskPython's Digital Clock",font="times 24 bold") digital.grid(row=0,column=2) nota=Label(root,text="hours minutes seconds",font="times 15 bold") nota.grid(row=3,column=2) root.mainloop()

    Цифровые часы в Python с использованием модулей TKinter и Time

    Последние слова …

    Вот как вы можете создать простые цифровые часы в программировании Python! Чего ты ждешь? Создайте свой собственный, попробовав код себя!

    Читайте ещё по теме:

    Источник

    Оцените статью