今日は、Pythonを使って数行のコードでSimple Digital Clockを作成する方法を学びます。
この時計を作るには、tkinterとtimeモジュールが必要です。
Python でデジタル時計を作るための必要条件
まず、Tkinterモジュールをインストールする必要があります。
もしこのモジュールがシステムにインストールされていない場合は、pipパッケージマネージャを使用してインストールすることができます。
C:UsersAdmin>pip install tkinter
|
Tkinterモジュールがシステムに正常にインストールされたら、準備は完了です。
Python でデジタル時計をコーディングする
今日はtkinterモジュールとtimeモジュールを使って時計を作ります。
1. Tkinterモジュール
TkinterはPythonの標準的なGUIライブラリです。
Tkinterの名前はTkインターフェースに由来します。
PythonとTkinterを組み合わせると、GUIアプリケーションを高速かつ容易に作成することができます。
TkinterはTk GUIツールキットに対する強力なオブジェクト指向のインタフェースを提供します。
TkinterはTk GUIツールキットに対するPythonのバインディングです。
この記事もチェック:PythonでTkinterを使ってGUIの電卓アプリを作成する方法
2. Timeモジュール
今回は、strftime()を使って、現在時刻をHour: 分。
今回は strftime() を使って現在の時刻を Hour: Minutes: Seconds 形式でパースします。
3. デジタル時計の実装
このコードでは、geometry()で表示するウィンドウの寸法を指定し、mainloop()で表示可能なウィンドウがすぐに終了しないようにします。
#import all the required libraries firstimport sys
from tkinter import *
#import time library to obtain current timeimport time
#create a function timing and variable current_timedef 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 windowroot=Tk()
#define size of the windowroot.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 clockclock=Label(root,font=("times",60,"bold"),bg="blue")
clock.grid(row=2,column=2,pady=25,padx=100)
timing()#create a variable for digital clockdigital=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() |
結果は以下の通りです。

Final Words…
以上、Pythonプログラミングで簡単なデジタル時計を作成する方法でした。