2017-07-03 117 views
-1

我想显示我显示消息的时间。我做到了,但时间不会更新。它仍然是我开始主循环的时候。下面我附上我的代码。我会欣赏任何形式的帮助,因为我是试图学习Python的noob。谢谢。Python Tkinter更新消息的时间

from tkinter import * 
    import time 

    time3 = time.strftime('%H:%M:%S') 

    def tick(): 
     global time1 
     time2 = time.strftime('%H:%M:%S') 
     clock.config(text=time2) 
     clock.after(200, tick) 

    root = Tk() 
    root.title("Test GUI") 
    time1 = ' ' 


    def newfile(): 
     message = (time3 + ':' + "Creating new file..... \n") 
     text.insert(0.0, message) 

    def openfile(): 
     message = (time3 + ':' + "Opening existing file..... \n") 
     text.insert(0.0, message) 

    def starttest(): 
     message = (time3 + ':' + "Start testing \n") 
     text.insert(0.0, message) 

    def stoptest(): 
     message = (time3 + ':' + "Stop testing \n") 
     text.insert(0.0, message) 

    topFrame = Frame(root) 
    topFrame.pack(side = TOP) 
    bottomFrame = Frame(root) 
    bottomFrame.pack(side = BOTTOM) 

    clock = Label(root, font=('times', 10, 'bold'), bd = 1, relief = SUNKEN, anchor = E) 
    but1 = Button(topFrame, text = "START", command = starttest) 
    but2 = Button(topFrame, text = "STOP", command = stoptest) 
    text = Text(topFrame, width = 35, height = 5, wrap = WORD) 

    clock.pack(side = BOTTOM, fill = X) 
    but1.grid(row = 3, column = 3) 
    but2.grid(row = 3, column = 4) 
    text.grid(row = 1, column = 0, columnspan =2, sticky = W) 

    menu = Menu(topFrame) 
    root.config(menu = menu) 

    subMenu = Menu(menu) 
    menu.add_cascade(label = "File", menu = subMenu) 
    subMenu.add_command(label = "New File", command = newfile) 
    subMenu.add_command(label = "Open File", command = openfile) 

    tick() 
    root.mainloop() 
+2

有与'tick'的压痕问题,我们可以不知道它在哪里结束。另外,你的'tk'对象缺少'mainloop'调用。另外,什么是“文字”?它没有在任何地方定义。你为什么有时在'time1'和'time2'上操作,有时候是'time3'? – kabanus

+0

你有做过什么研究吗?这个网站上有很多关于倒数计时器和使用tkinter的时钟的问题。 –

+0

嗨,我很抱歉,我应该包括我现在所做的所有代码。我做了一些研究,我发现问题应该在时间3,应该包括更多的代码行来实时更新它,但是我被困住了。希望任何人给我的想法。再次感谢。 –

回答

0

首先,我建议你写的一类应用程序(见Best way to structure a tkinter application),因为它会更有组织。

class Timer(tk.Frame): 
    def __init__(self, parent): # create the time frame... 
     self.parent = parent 
     self.time_1 = " " 
     self.time_label = tk.Label(text=self.time_1) 
     self.time_label.pack() 
     self.random_lbl = tk.Label(text="hi lol") 
     self.random_lbl.pack() 
     self.update_clock() # we start the clock here. 

当你更新的时候,坚持你所用的时间(比方说,在这种情况下,它的TIME_1)变量:

def update_clock(self): # update the clock... 
     self.time_2 = time.strftime("%H:%M:%S") 
     self.time_1 = self.time_2 # we are changing time_1 here. 
     self.time_label.config(text=self.time_1) 
     self.parent.after(200, self.update_clock) # then we redo the process. 

root = tk.Tk() # create the root window. 
timer = Timer(root) 
root.mainloop() 
+0

快速指针:修改时间戳信息,只需添加'+“等等等等等等。 –

+0

我想问一下按下按钮时是否可以打印当前的时间。我尝试了你提到的方法,但是现在每当我尝试在我的显示框上打印时间时,它都会一直显示相同的时间。 –