raspberrypiでGUIカウントダウンダイマーを作る
今回作ったもの
今回は設定した時間分カウントダウンをし、画面にGUI表示するソフトをpythonとraspberrypiで作ってみました。
pythonで使えるtkinterというUGI作成パッケージを使用してカウントダウンしたものをターミナル上ではなく、GUIで表示します。
環境
Raspberry pi 3B+
python 3.7.3
tkinter
pillow
準備
sudo apt update sudo apt remove python3-pil sudo apt install python3-tk pip3 install pillow
詰まった部分
画像ライブラリのpillowはpythonをインストールしたときにはじめから入っているのですが、それだと上手く動かなかったので、アンインストールしてから最新版を再インストールしました。
完成品
カウントが10からスタートして0まで表示されます。
ソースコード
import math import json import requests import os from tkinter import * import tkinter.ttk as ttk from datetime import datetime, timedelta from time import sleep target_time = 20 # メインウィンドウ作成 root = Tk() # メインウィンドウサイズ root.geometry("1024x600") # メインウィンドウタイトル root.title("count") # MainFrame クラス class MainFrame(ttk.Frame): # コンストラクタ def __init__(self, master=None, **kwargs): # 親クラスのコンストラクタを呼び出す super().__init__(master, **kwargs) # create_widgets を呼び出す self.create_widgets() # ウィジェットを作成 def create_widgets(self): # フレームを作成 self.frame = Frame(self, bg="white", bd=0, height=460, relief="flat") # タイマーカウント表示 self.wp = Label(self.frame, text="", bg="white", font=("", 40, "bold"), anchor="w") self.wp.place(width=740, x=150, y=350) # フレームを配置 self.frame.grid(row=0, column=0, columnspan=8, sticky="news") self.rowconfigure(0,weight=1) self.rowconfigure(1,weight=1) self.rowconfigure(2,weight=1) self.rowconfigure(3,weight=1) self.rowconfigure(4, weight=1) for i in range(8): self.columnconfigure(i, weight=1) # メインフレームを配置 app = MainFrame(root) app.pack(side=TOP, expand=1, fill=BOTH) # メインウィンドウを閉じる def wm_close(): root.destroy() # 閉じるボタン作成 btn = Button(root, text=" X ", font=('', 16), relief=FLAT, command=wm_close) # 画面がリサイズされたとき def change_size(event): # ボタンの位置を右上に btn.place(x=root.winfo_width() - 60, y=14) # 画面のリサイズをバインドする root.bind('<Configure>', change_size) # メインウィンドウの最大化 #root.attributes("-zoom", "1") root.attributes("-fullscreen", "1") counter_time = 0 count_time_flag = 1 def count_down_time(): global counter_time global count_time_flag if count_time_flag == 1: counter_time = 5 count_time_flag = 0 # フラグを下げてカウントがリセットされないようにする counter_time -= 1 #print(counter_time) if counter_time < 0: return 0 t = "インターバル残り時間:{0}".format(counter_time) app.wp.configure(text=t) root.after(1000, count_down_time) count_down_time() # メインループ root.mainloop()