如何在类[Python 3.x]中使用tick()

时间:2017-09-19 13:20:38

标签: python-3.x function class clock

所以基本上我正在做一个学校项目,它涉及到课程和tkinter,我想把我的tick()函数放到课堂上,以便我可以在我的程序中有一个时钟,但我似乎无法当我把它添加到一个类时让它工作?

任何帮助/建议都将不胜感激。

import urllib.request
from tkinter import *
from tkinter import ttk
import time


class MainWindow(object):
    def __init__(self):
        self.root = Tk()
        self.root.state("zoomed")  #to make it full screen
        self.root.title("Vehicle Window Fitting - Management System")
        self.root.configure(bg="grey80")

        self.frame_1 = Frame(self.root, width=1350, height=50)
        self.frame_1.pack(side=TOP, fill=X, expand=1, anchor=N)

        self.title_lbl = Label(self.frame_1, font=('arial', 12, 'bold'), text="Vehicle Window Fitting - Management System", bd=5, anchor=W)
        self.title_lbl.pack(side=LEFT) #puts title on left side

        self.clockFrame = Frame(self.frame_1, width=100, height=50, bd=4, relief="ridge")
        self.clockFrame.pack(side=RIGHT)#puts clock frame on right
        self.clockLabel = Label(self.clockFrame, font=('arial', 12, 'bold'), bd=5, anchor=E)
        self.clockLabel.pack() #puts the number in the clock frame

    def tick(self, curtime=''):  #acts as a clock, changing the label when the time goes up
        newtime = time.strftime('%H:%M:%S')
        if newtime != curtime:
            curtime = newtime
            self.clockLabel.config(text=curtime)
        self.clockLabel.after(200, tick, curtime)

(此处更多代码但不相关) 然后:

window = MainWindow()
clock = window.tick()

一切都在正确,但时钟不会改变它是静止的。我已经设法让它在课外工作,但我如何将它实现到一个类中?

1 个答案:

答案 0 :(得分:1)

通过更改

修复
self.clockLabel.after(200, tick, curtime)

self.clockLabel.after(200, self.tick, curtime)

花了很长时间才弄明白哈哈