好了,所以這是我將與你的代碼做來完成你正在嘗試做的。
首先讓我們確保我們有正確的進口。
from tkinter import *
import datetime
import time
我創造了這個doNothing()
功能作爲我不是目前正在測試的任何命令的佔位符。
def doNothing():
pass
現在的方式,你有你Clockupdate(time):
功能會導致標籤被你點擊時鐘按鈕每次增加。所以這可能不是你想要的,因爲它只是添加新的標籤而不是替換現有的標籤。看看這個功能。我所做的全部是.config()
文本作爲函數的時間參數。請注意,您不需要重新定義時間標籤或類別的任何時間,只需使用時間作爲您的可用空間。
def Clockupdate(time):
timerefresher.config(text = time)
,如果你想使用一類特定原因,但我認爲你應該只使用一個函數在這裏我不知道。也儘量保持你的報價一致。我知道它們是可以互換的,但它是保持它們一致的良好實踐。
def secondrefesher():
newtime = ""
oldtime = datetime.datetime.now()
a = str(oldtime.hour)
b = str(oldtime.minute)
c = str(oldtime.second)
curtime = (a + ":" + b + ":" + c)
if curtime != newtime:
newtime = curtime
Clockupdate(newtime)
注意我始終把命令在按鈕的任何配置的結束。它有助於管理代碼,因此您可以在滾動代碼時檢查每行的結尾。我也改變了Pressme的命令,所以我可以測試代碼。您沒有提供Presstoshowtextandpic的代碼,也無法用該部分測試代碼。請記住在這裏提問時要使用MCVE。
root = Tk()
mainlabel = Label(root, text="Hey this is working!")
Pressme = Button(root, text = "Press me!", bg = "red", fg = "white", command = doNothing)
Clock = Button(root, text = "Clock?", bg = "blue", fg = "white", command = secondrefesher)
Photo = PhotoImage(file = "test.png")
ShowPhoto = Label(root, image = Photo)
在這裏,我創建了一次的時間標籤,然後你可以調用更新函數,所有你想改變文本到當前時間。
timerefresher = Label(root, text = "")
timerefresher.pack()
mainlabel.pack()
Pressme.pack()
Clock.pack()
root.mainloop()
這是我想完成的代碼看起來應該像你。
from tkinter import *
import datetime
import time
def Clockupdate(time):
timerefresher.config(text = time)
def secondrefesher():
newtime = ""
oldtime = datetime.datetime.now()
a = str(oldtime.hour)
b = str(oldtime.minute)
c = str(oldtime.second)
curtime = (a + ":" + b + ":" + c)
if curtime != newtime:
newtime = curtime
Clockupdate(newtime)
root = Tk()
mainlabel = Label(root, text = "Hey this is working!")
Pressme = Button(root, text = "Press me!", bg = "red", fg = "white", command = Presstoshowtextandpic)
Clock = Button(root, text = "Clock?", bg = "blue", fg = "white", command = secondrefesher)
Photo = PhotoImage(file = "test.png")
ShowPhoto = Label(root, image = Photo)
timerefresher = Label(root, text = "")
timerefresher.pack()
mainlabel.pack()
Pressme.pack()
Clock.pack()
root.mainloop()
編輯:
如果你要創建一個時鐘,始終是積極的,不需要你點擊就可以使用.after()
按鈕。
看看這個例子。
from tkinter import *
import datetime
import time
root = Tk()
mainlabel = Label(root, text = "Hey this is working!")
Photo = PhotoImage(file = "test.png")
timerefresher = Label(root, text = "")
timerefresher.pack()
status_time = ""
def tick():
global status_time
time2 = time.strftime("%H:%M:%S")
if time2 != status_time:
status_time = time2
timerefresher.config(text = time2)
timerefresher.after(200, tick)
tick()
mainlabel.pack()
root.mainloop()
請提供您的進口,以便我們可以查看您是否擁有您需要的所有進口產品。 –