import tkinter,time
canvas=tkinter.Canvas(width=500,height=500,bg="white")
canvas.pack()
canvas.create_text(250,250,text="0:0:0",font="Arial 70 bold")
global b
def cl_e():
b=False
def cl_s():
h=0
m=0
s=0
while b:
if s<60:
s+=1
canvas.delete("all")
time.sleep(1)
canvas.create_text(250,250,text=str(h)+":"+str(m)+":"+str(s),font="Arial 70 bold")
canvas.update()
elif m<60:
s=0
m+=1
canvas.delete("all")
canvas.create_text(250,250,text=str(h)+":"+str(m)+":"+str(s),font="Arial 70 bold")
canvas.update()
else:
s=0
m=0
h+=1
canvas.delete("all")
canvas.create_text(250,250,text=str(h)+":"+str(m)+":"+str(s),font="Arial 70 bold")
canvas.update()
b=True
start=tkinter.Button(text="Start",command=cl_s())
end=tkinter.Button(text="End",command=cl_e())
start.pack()
end.pack()
As you can see, I am trying to start the cl_s() function only when the button "Start" is pressed and the cl_e() funkcion when the button "End" is pressed. The thing is the buttons do not appear in the canvas and the function cl_s() starts on its own. I wanted to achieve that when the "Start" button is pressed the timer will start and when the "End" button is pressed the timer will stop. I used a global variable "b" so when it is True the timer runs and when it is false the timer will stop, but it does not work. Without the "b" variable the button are visible, but with it they disappear.
Thank you all. The problem was that the term "global b" shoud have been at the begining of all the funkcions.
import tkinter,time
canvas=tkinter.Canvas(width=500,height=500,bg="white")
canvas.pack()
canvas.create_text(250,250,text="00:00:00",font="Arial 70 bold")
def cl_e():
global b
b=False
clock()
def cl_s():
global b
b=True
clock()
def clock():
global b
h=0
m=0
s=0
while b:
canvas.delete("all")
if s<60:
s+=1
time.sleep(1)
elif m<60:
s=0
m+=1
else:
s=0
m=0
h+=1
if h<10 and m<10 and s<10:
canvas.create_text(250,250,text="0"+str(h)+":0"+str(m)+":0"+str(s),font="Arial 70 bold")
elif h<10 and m<10 and s>=10:
canvas.create_text(250,250,text="0"+str(h)+":0"+str(m)+":"+str(s),font="Arial 70 bold")
elif h<10 and m>=10 and s<10:
canvas.create_text(250,250,text="0"+str(h)+":"+str(m)+":0"+str(s),font="Arial 70 bold")
elif h<10 and m>=10 and s>=10:
canvas.create_text(250,250,text="0"+str(h)+":"+str(m)+":"+str(s),font="Arial 70 bold")
elif h>=10 and m<10 and s<10:
canvas.create_text(250,250,text=str(h)+":0"+str(m)+":0"+str(s),font="Arial 70 bold")
elif h>=10 and m<10 and s>=10:
canvas.create_text(250,250,text=str(h)+":0"+str(m)+":"+str(s),font="Arial 70 bold")
elif h>=10 and m>=10 and s<10:
canvas.create_text(250,250,text=str(h)+":"+str(m)+":0"+str(s),font="Arial 70 bold")
else:
canvas.create_text(250,250,text=str(h)+":"+str(m)+":"+str(s),font="Arial 70 bold")
canvas.update()
start=tkinter.Button(text="Start",command=cl_s)
end=tkinter.Button(text="End",command=cl_e)
start.pack()
end.pack()