我正在尝试创建一个GUI,该GUI将显示当前本地时间并在您按下“ Lap”按钮时为您提供时间输出。到目前为止,我已经创建了时钟和按钮,但是似乎无法弄清楚如何在窗口中创建一个输出框,该窗口在按下按钮时将显示时间戳。我几乎没有编程经验,所以将不胜感激!
我附上了到目前为止的内容:
import tkinter
import time
class Clock(tkinter.Label):
def __init__(self, parent=None, seconds=True, colon=False):
tkinter.Label.__init__(self, parent)
self.display_seconds = seconds
if self.display_seconds:
self.time = time.strftime('%I:%M:%S')
else:
self.time = time.strftime('%I:%M %p').lstrip('0')
self.display_time = self.time
self.configure(text=self.display_time)
if colon:
self.blink_colon()
self.after(200, self.tick)
def tick(self):
if self.display_seconds:
new_time = time.strftime('%I:%M:%S')
else:
new_time = time.strftime('%I:%M %p').lstrip('0')
if new_time != self.time:
self.time = new_time
self.display_time = self.time
self.config(text=self.display_time)
self.after(200, self.tick)
def timestamp():
print(time.strftime("%I:%M:%S"))
if __name__ == "__main__":
window = tkinter.Tk()
frame = tkinter.Frame(window, width=800, height=800)
frame.pack()
tkinter.Label(frame, text="Current time: ").pack()
clock1 = Clock(frame)
clock1.pack()
clock1.configure(bg='white', fg='black', font=("helvetica", 65))
tkinter.Label(frame, text=" ").pack()
b = tkinter.Button(frame, text='Quit', command=quit)
b.pack(side=tkinter.RIGHT)
b2 = tkinter.Button(frame, text='Lap', command=timestamp)
b2.pack(side=tkinter.LEFT)
window.mainloop()
我需要帮助在窗口中创建一个输出框,该输出框将在按下“ Lap”按钮时显示时间。
答案 0 :(得分:1)
您可以创建一个ScrolledText
,并在按下按钮时使用insert("end", value)
命令将其插入。这是增强的代码。
import tkinter
import time
from tkinter import scrolledtext
class Clock(tkinter.Label):
def __init__(self, parent=None, seconds=True, colon=False):
tkinter.Label.__init__(self, parent)
self.display_seconds = seconds
if self.display_seconds:
self.time = time.strftime('%I:%M:%S')
else:
self.time = time.strftime('%I:%M %p').lstrip('0')
self.display_time = self.time
self.configure(text=self.display_time)
if colon:
self.blink_colon()
self.after(200, self.tick)
def tick(self):
if self.display_seconds:
new_time = time.strftime('%I:%M:%S')
else:
new_time = time.strftime('%I:%M %p').lstrip('0')
if new_time != self.time:
self.time = new_time
self.display_time = self.time
self.config(text=self.display_time)
self.after(200, self.tick)
def timestamp():
print(time.strftime("%I:%M:%S"))
if __name__ == "__main__":
window = tkinter.Tk()
frame = tkinter.Frame(window, width=800, height=800)
frame.pack()
tkinter.Label(frame, text="Current time: ").pack()
text = scrolledtext.ScrolledText(frame, height=10) ##
text.pack() ##
clock1 = Clock(frame)
clock1.pack()
clock1.configure(bg='white', fg='black', font=("helvetica", 65))
tkinter.Label(frame, text=" ").pack()
b = tkinter.Button(frame, text='Quit', command=quit)
b.pack(side=tkinter.RIGHT)
b2 = tkinter.Button(frame, text='Lap', command=lambda :text.insert("end", time.strftime("%I:%M:%S")+'\n')) ##
b2.pack(side=tkinter.LEFT)
window.mainloop()