我想显示我显示信息的时间。我做到了,但时间不会更新。它将保持为我启动主循环的时间。下面我附上了我的代码。我会感激任何形式的帮助,因为我是一个努力学习Python的菜鸟。谢谢。
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()
答案 0 :(得分: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.
当您更新时间时,请坚持使用您当时使用的变量(例如,在这种情况下,它是时间_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()