Tkinterのを使用して、タイマーを作成する方法?
-
18-09-2019 - |
質問
私は、PythonのTkinterのライブラリとプログラムをコーディングする必要があります。
私の大きな問題は、私はのタイマーまたはのクロックは、のように作成する方法がわからないということです
hh:mm:ss
。
私は(それは私が行うには方法がわからないものだ)、それは自分自身を更新する必要があります。
解決
Tkinterのルートウィンドウは、一定時間後に呼び出される関数をスケジュールするために使用することができるafter
と呼ばれるメソッドを有します。その関数自体はあなたが自動的に定期的なイベントを設定しているafter
呼び出す場合。
ここで作業例です。
# for python 3.x use 'tkinter' rather than 'Tkinter'
import Tkinter as tk
import time
class App():
def __init__(self):
self.root = tk.Tk()
self.label = tk.Label(text="")
self.label.pack()
self.update_clock()
self.root.mainloop()
def update_clock(self):
now = time.strftime("%H:%M:%S")
self.label.configure(text=now)
self.root.after(1000, self.update_clock)
app=App()
時間に正確に実行される機能を保証するものではありませんafter
ベア心インチそれだけのスケジュールのジョブは一定時間後に実行されます。アプリはTkinterにはシングルスレッドであるため、それが呼び出される前に遅延が発生する場合があり忙しいです。遅延は、典型的には、マイクロ秒単位で測定される。
他のヒント
frame.after()ではなくトップレベルアプリケーションを使用してのpython3クロック例。またSTRINGVAR()
とラベルを更新示し#!/usr/bin/env python3
# Display UTC.
# started with https://docs.python.org/3.4/library/tkinter.html#module-tkinter
import tkinter as tk
import time
def current_iso8601():
"""Get current date and time in ISO8601"""
# https://en.wikipedia.org/wiki/ISO_8601
# https://xkcd.com/1179/
return time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.now = tk.StringVar()
self.time = tk.Label(self, font=('Helvetica', 24))
self.time.pack(side="top")
self.time["textvariable"] = self.now
self.QUIT = tk.Button(self, text="QUIT", fg="red",
command=root.destroy)
self.QUIT.pack(side="bottom")
# initial time display
self.onUpdate()
def onUpdate(self):
# update displayed time
self.now.set(current_iso8601())
# schedule timer to call myself after 1 second
self.after(1000, self.onUpdate)
root = tk.Tk()
app = Application(master=root)
root.mainloop()
from tkinter import *
import time
tk=Tk()
def clock():
t=time.strftime('%I:%M:%S',time.localtime())
if t!='':
label1.config(text=t,font='times 25')
tk.after(100,clock)
label1=Label(tk,justify='center')
label1.pack()
clock()
tk.mainloop()
私は(ただし、それはかもしれMVPパターンを使用して単純なタイマーを作成しました その単純なプロジェクトのためにやり過ぎ)。これは、開始/一時停止し、停止ボタンを終了しました。 MM:SS形式で時間をHHに表示されます。タイムカウントが第二、タイマーが開始された時刻と現在時刻との差を数回実行しているスレッドを使用して実装されます。
githubののの所属していません StackOverflow