也不會一次我加self.methodToRun =功能 但功能不被調用顯示任何錯誤。(這是什麼情況在Python傳遞函數的一類3
>>> func()
1
>>> ================================ RESTART ================================
>>>
>>> tt = timer_tick(1,func)
>>> tt.start()
>>>)
這裏的代碼
import time
def func():
print('1')
class timer_tick:
def __init__(self, num, function):
self.delay = num
self.methodToRun = function
self.timercondition = False
def start(self):
timercondition = True
self.timer()
def timer(self):
while self.timercondition:
self.methodToRun()
time.sleep(self.delay)
def stop(self):
timercondition = False
def method1():
return 'hello world'
def method2(methodToRun):
result = methodToRun()
return result
好,我發現這一點的同時寫一個秒錶程序,即定時效果可以通過tkinter.Tk.after()函數來實現。我能夠加入控制停止,暫停並用它重置定時器。
import tkinter
import random
import time
frame = tkinter.Tk()
frame.title("Stopwatch")
frame.geometry('500x300')
t='00:00.0'
helv30 = ('Helvetica', 30)
num = 0
timer = 1
def timerhand():
global num,n
num += 1
formate(num)
def formate(num):
global t,n
if (get_seconds(num) >= 0 and get_seconds(num)<10):
if (num%100)%10 == 0 and (num//600) < 10 :
t ='0'+ str(get_minutes(num)) + ':'+'0' + str(get_seconds(num))+'.0'
elif (num//600) < 10:
t ='0'+ str(get_minutes(num)) + ':'+'0' + str(get_seconds(num))
elif (num%100)%10 == 0:
t =str(get_minutes(num)) + ':'+'0' + str(get_seconds(num))+'.0'
else:
t = str(get_minutes(num)) + ':'+'0' + str(get_seconds(num))
else:
if (num%100)%10 == 0 and (num//600) < 10 :
t ='0'+ str(get_minutes(num)) + ':' + str(get_seconds(num))+'.0'
elif (num//600) < 10:
t ='0'+ str(get_minutes(num)) + ':' + str(get_seconds(num))
elif (num%100)%10 == 0:
t =str(get_minutes(num)) + ':' + str(get_seconds(num))+'.0'
else:
t = str(get_minutes(num)) + ':' + str(get_seconds(num))
def get_minutes(num):
return (num//600)
def get_seconds(num):
return (num%600)/10
def stop():
global timer,t,num
timer = 0
t = '00:00.0'
num = 0
def pause():
global timer,t
timer = 0
def start():
global timer
timer = 1
clock()
canvas1 = tkinter.Canvas(frame,width = 300, height = 100,bg = 'black')
t_message = canvas1.create_text(150,50, text = t , fill = 'blue', font = helv30)
b1= tkinter.Button(frame,text = "Stop",command = stop)
b1.pack(side ="bottom")
b2= tkinter.Button(frame,text = "Start",command = start)
b2.pack(side ="bottom")
b2= tkinter.Button(frame,text = "Pause",command = pause)
b2.pack(side ="bottom")
#here is the time function implementation
def clock():
global canvas1,t_message
timerhand()
canvas1.itemconfig(t_message, state = 'hidden')
t_message = canvas1.create_text(150,50, text = t , fill = 'blue', font = helv30)
canvas1.pack()
if timer == True:
frame.after(100,clock)
clock()
canvas1.pack()
frame.mainloop()
所以我一直在尋找各種方法來實現這一目標沒有Tkinter的模塊
你想要將該函數傳遞給該類中的哪些方法?你可以像普通的參數一樣傳球。 –
'stop()'應該設置'timercondition = False'。 – glglgl
而'self.timercondition:'應該夠了。 – glglgl