如何在Entry小部件中插入当前时间

4

当前代码:

from Tkinter import *
import time

Time = time.strftime('%H:%M%p')
print Time

root = Tk()
root.option_add('*Font', 'courier 12')
root.option_add('*Background', 'grey')
root.configure(bg = 'grey')

w, h = 203, 50
x, y = (root.winfo_screenwidth()/2) - (w/2), (root.winfo_screenheight()/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

Time = Entry(root, relief = RIDGE, bd = 5, width = 16, cursor = 'plus', fg = 'red', selectforeground = 'red', selectbackground = 'black')
Time.place(x = 0, y = 0)
Time.insert(0, Time)

root.title('Time') 
root.mainloop()

以上代码是我实际代码的一部分,问题在于当我试图将当前时间插入输入小部件时,它显示为十进制数,但在控制台中显示正常。为什么会这样呢?

以下是屏幕截图:

enter image description here

我正在使用Python 2.7.5。

1个回答

1
你正在用一个 Entry 组件覆盖变量 Time,因此将其放入另一个变量中,例如 time:
#You initialize it:
Time = time.strftime('%H:%M%p')
# Then you overwrite it:
Time = Entry(root, relief = RIDGE, bd = 5, width = 16, cursor = 'plus', fg = 'red', selectforeground = 'red', selectbackground = 'black')

改为这样做:

time = time.strftime('%H:%M%p')
print time

Time = Entry(root, relief = RIDGE, bd = 5, width = 16, cursor = 'plus', fg = 'red', selectforeground = 'red', selectbackground = 'black')
Time.place(x = 0, y = 0)
Time.insert(0, time)

输出:

enter image description here


1
不错,我用了Time变量来做多个事情,谢谢K Man :D - KingMak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接