Development Tip

tkinter를 사용하여 타이머를 만드는 방법은 무엇입니까?

yourdevel 2020. 11. 1. 18:46
반응형

tkinter를 사용하여 타이머를 만드는 방법은 무엇입니까?


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 패턴을 사용하여 간단한 타이머를 만들었습니다 (단순한 프로젝트에서는 과도 할 수 있음). 종료, 시작 / 일시 중지 및 중지 버튼이 있습니다. 시간은 HH : MM : SS 형식으로 표시됩니다. 시간 계산은 1 초에 여러 번 실행되는 스레드와 타이머가 시작된 시간과 현재 시간의 차이를 사용하여 구현됩니다.

github의 소스 코드


I have a simple answer to this problem. I created a thread to update the time. In the thread i run a while loop which gets the time and update it. Check the below code and do not forget to mark it as right answer.

from tkinter import *
from tkinter import *
import _thread
import time


def update():
    while True:
      t=time.strftime('%I:%M:%S',time.localtime())
      time_label['text'] = t



win = Tk()
win.geometry('200x200')

time_label = Label(win, text='0:0:0', font=('',15))
time_label.pack()


_thread.start_new_thread(update,())

win.mainloop()

참고URL : https://stackoverflow.com/questions/2400262/how-to-create-a-timer-using-tkinter

반응형